Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Prolog how to print first 3 elements in a list

Tags:

prolog

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.
like image 277
user236501 Avatar asked Dec 06 '22 18:12

user236501


2 Answers

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.

like image 162
svick Avatar answered Dec 28 '22 23:12

svick


If you always have at least tree elements ist very simple

 print_first_three([A,B,C|_]) :- print(A), print(B), print(C).
like image 27
Joe Lehmann Avatar answered Dec 28 '22 23:12

Joe Lehmann