Prolog how to print first 3 elements in a list
How can I print the first 3 elements in a list.
开发者_开发知识库I have a print method
print([]).
print([X]) :- !, write(X).
print([X|T]) :- write(X), write(', '), print(T), nl.
In Prolog, the typical way to implement iteration is recursion:
print(0, _) :- !.
print(_, []).
print(N, [H|T]) :- write(H), nl, N1 is N - 1, print(N1, T).
If we reached zero or have an empty list, do nothing. If we should do something, print the first item in the list, compute the new N
and recursively call itself.
The cut (!
) in the first clause is necessary, otherwise we would need a condition for N
in the last one.
If you always have at least tree elements ist very simple
print_first_three([A,B,C|_]) :- print(A), print(B), print(C).
精彩评论