如何逐个打印列表中的项目

时间:2014-03-25 21:08:39

标签: prolog

我在findall的列表中有我的答案,列表叫做答案。 现在答案可以包含0个,1个或更多项目。

0回答我可以用display_answers([])来解决。

我可以用display_answer([X])解决1个答案。

我可以做多于1个display_answer([X | X]),然后使用foreach打印所有答案吗? 或者有更好的方法吗?

鲁洛夫

Edit1: 我试过这个:

% Displays the output of siblings(X,Y) and takes care that 
% there are no duplicates.
display_siblings(Person) :-
     findall(Person-Y, siblings(Person,Y), Sibs),
     display_the_siblings(Sibs).

% Display a message if there are no siblings found. 
display_the_siblings([]) :-
       write('Er zijn geen zussen/broers bekend').  

% Displays a message if one sibling is found.
display_the_siblings([X-Y]) :-
        write('The enigste broer of zuster is '),
        write(Y).

% Display a message if there are more then 1 siblings found.
display_the_siblings([[X-Y|X-Y]) :-
        write('Alle zusterparen zijn : \n'),

但如果我使用递归,那么当Sibs为1时,则使用错误的谓词。 所以问题仍然是我作为参数使最后一个谓词工作。

2 个答案:

答案 0 :(得分:0)

我的序言有点生疏,但一般来说,你使用[Head | Tail]在列表中进行递归。类似的东西:

display_answer([]) :- !.
display_answer( [Head|Tail] ) :-
   print( Head ),
   display_answer( Tail ).

希望它有所帮助。玩得开心......

答案 1 :(得分:0)

我的〜/ .plrc(Linux上的SWI-Prolog基本配置文件)这个定义

setln(Pattern, Goal) :-
    setof(Pattern, Goal, List), maplist(writeln, List).

只允许对解决方案进行排序显示,以备我需要时...例如

?- setln(M, current_module(M)).
ansi_term
apply
arithmetic
base32
...
相关问题