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).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With