简体   繁体   English

如何防止序幕否?

[英]how to prevent no in prolog?

Prolog, recursive function: i want it to print the C with each element of the list for example: C=30 and [H|T]= [-9,-10,-30] Prolog,递归函数:我希望它用列表的每个元素打印C,例如:C = 30和[H | T] = [-9,-10,-30]

myfunc(C,[H|T]):-   
    (\+([H|T]=[])),
    write(C), write(' with '), write(H), nl,
    myfunc(C,T).

i check at the beginning that the head of the list is not empty. 我首先检查列表的开头是否为空。 it gives me this output 它给了我这个输出

30 with -9
30 with -10
30 with -30

    (32 ms) no

this output is what i want but i dont want to get a 'no' at the end because this makes the parent function to fail as well! 此输出是我想要的,但我不想在最后得到“ no”,因为这会使父函数也失败! how can i remove it and put a 'yes' instead? 我如何将其删除并改为“是”?

Simple way: just add a base case with the empty list. 简单方法:只需添加一个带有空列表的基本案例。

myfunc(_, []) :- !.

myfunc(C,[H|T]):-   
    write(C), write(' with '), write(H), nl,
    myfunc(C,T).

test: 测试:

?- myfunc(30, [1, 2, 3]).
30 with 1
30 with 2
30 with 3
true.

I don't know if this is the best way to do that, but you didn't give us much details about your whole program, so I opted for a small modification of your predicate. 我不知道这是否是最好的方法,但是您没有为我们提供有关整个程序的详细信息,因此我选择对谓词进行一些小的修改。

If you have maplist in your Prolog, you can write 如果您的Prolog中有地图列表,则可以编写

myfunc(N, L) :-
    maplist(my_write(N), L).


my_write(N, Val) :-
    format('~w with ~w~n', [N, Val]).

With SWI-Prolog and module lambda 带有SWI-Prolog和模块lambda

:- use_module(library(lambda)).

myfunc(N, L) :-
    maplist(\X^format('~w with ~w~n', [N, X]), L).

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM