Reputation: 39
I can't display list of list in prolog please help me for example : I have this list : [[1,2,3][4,5][6,8,7][6,9]] I want to delete this [ [] [] [] [] ] and just display content: 1 2 3 4 5 6 8 7 6 9
I have tried this
WriteListe([]).
write_liste([X|Xs]) :-
format('-~w~n', [X]),
write_liste(Xs).
But when i call WriteListe(L) i have this result L=[] -_6782 L = [_6782] .....
? Thanks you
Upvotes: 0
Views: 384
Reputation: 71119
Every non-empty list [A|B]
consists of its head element A
and the rest of its elements, a list B
. Otherwise it is an empty list, []
:
write_liste(X):- /* e.g. write_liste([[1,2,3],[4,5]). */
X = [A|B] -> write_liste( ... ), /* recurse on "car" */
write_liste( ... ) ; /* recurse on "cdr" */
X = [] -> true /* skip it */ ;
/* else */ format('~w ', X). /* we've reached the list's fringe */
Try to fill in the blanks.
In lisp this is informally known as car
⁄ cdr
recursion. We process the "car
" i.e. the head element, and the cdr
i.e. the rest of the elements. And if it can't be taken apart, then it's an atomic element. Since each chain of such cons
nodes ([A|B]
in Prolog) ends in a sentinel value, an empty list []
which also cannot be taken apart, we skip that, as we're interested only in the actual elements, not in any artificial effects of representation.
Put another way, []
is empty, so there's nothing in it to be printed.
Upvotes: 2