These predicates enable lists to be manipulated and trasversed.
length/2length(List, Length) is true iff integer Length equals the number of elements in list List. In particular, if List is instantiated to a list of determinate length, then Length will be unified with this length. If List is of indeterminate length and Length is instantiated to an integer, then List will be unified with a list of length Length, and the list elements are unique variables. Finally, if Length is unbound then Length will be unified with all possible lengths of List.
Templates and modes for the predicate are as follows:
length(?list, ?length)
Let's start with some simple tests verifying success or failure of single goals.
| alice.tuprolog.SimpleGoalFixture | |
| goal | success() |
| length('scarlet', 7). | false |
| length(A, -1). | false |
Now we run some tests also verifying the unification for some of the variables in goals.
First of all, let's start an appropriate fixture containing an engine.
| fit.ActionFixture | |
| start | alice.tuprolog.EngineFixture |
Then, ask the engine to solve a query, and check variable bindings.
| fit.ActionFixture | ||
| enter | query | length([], 0). |
| check | hasSolution | true |
| enter | query | length(X, 5). |
| check | hasSolution | true |
| enter | variable | X |
| check | binding | [_, _, _, _, _] |
| check | hasAnotherSolution | false |
| enter | query | length([1, 2 | T], X). |
| check | hasSolution | true |
| enter | variable | X |
| check | binding | 2 |
| enter | variable | T |
| check | binding | [] |
| check | hasAnotherSolution | true |
| enter | variable | X |
| check | binding | 3 |
| enter | variable | T |
| check | binding | [_] |
| check | hasAnotherSolution | true |
| enter | variable | X |
| check | binding | 4 |
| enter | variable | T |
| check | binding | [_, _] |
| enter | query | length(L, S). |
| check | hasSolution | true |
| enter | variable | L |
| check | binding | [] |
| enter | variable | S |
| check | binding | 0 |
| check | hasAnotherSolution | true |
| enter | variable | L |
| check | binding | [_] |
| enter | variable | S |
| check | binding | 1 |
| check | hasAnotherSolution | true |
| enter | variable | L |
| check | binding | [_, _] |
| enter | variable | S |
| check | binding | 2 |
Other candidates for similar tests are: append/3, member/2, no_duplicates/2, quicksort/3, reverse/2, delete/3, element/3.
Run the tests!
The results of the tests for List management are as follows:
| fit.Summary |