开发者

Prolog how to print first 3 elements in a list

开发者 https://www.devze.com 2023-04-12 06:58 出处:网络
How can I print the first 3 elements in a list. 开发者_开发知识库 I have a print method print([]).

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).
0

精彩评论

暂无评论...
验证码 换一张
取 消