Prolog 绑定参数 [英] Prolog binding arguments
问题描述
在 sicstus prolog 中,有一个谓词:
In sicstus prolog, there's a predicate:
maplist(:Pred, +List)
Pred
应该只接受一个参数 - List
元素.如何通过定义第一个参数的 2 参数谓词?在其他语言中,它会被写成:
Pred
is supposed to take just one argument - List
element. How can I pass a 2-argument predicate, with first argument defined? In other languages it would be written as:
maplist(pred.bind(SomeValue), List)
推荐答案
maplist(P_1, Xs)
会为 call(P_1, X)
的每个元素调用 call(P_1, X)
代码>Xs.内置谓词call/2
向P_1
添加另一个参数,然后用call/1
调用它.为了表明需要进一步的参数,使用像 P_1
这样的名称非常有帮助,意思是需要一个额外的参数".
maplist(P_1, Xs)
will call call(P_1, X)
for each element of Xs
. The built-in predicate call/2
adds one further argument to P_1
and then calls this with call/1
. To indicate that a further argument is needed, it is very helpful to use a name like P_1
meaning "one extra argument is needed".
因此,如果您已经有一个元数为 2 的谓词,例如 (=)/2
,您将把 =(2)
传递给 maplist:
So if you have already a predicate of arity 2, say, (=)/2
, you will pass =(2)
to maplist:
?- maplist(=(2), Xs).
Xs = [] ;
Xs = [2] ;
Xs = [2,2] ...
不幸的是,由于 SICStus 库中的定义不正确,请使用以下定义:
Since the definition in SICStus' library is unfortunately, incorrect, rather use the following definition:
:- meta_predicate(maplist(1,?)).
:- meta_predicate(maplist_i(?,1)).
maplist(P_1, Xs) :-
maplist_i(Xs, P_1).
maplist_i([], _P_1).
maplist_i([E|Es], P_1) :-
call(P_1, E),
maplist_i(Es, P_1).
有关更多信息,请参阅此答案.
See this answer for more.
只是关于列表列表的一个很好的例子.
Just a nice further example about lists of lists.
?- Xss = [[A],[B,C]], maplist(maplist(=(E)), Xss).
Xss = [[E], [E, E]],
A = B, B = C, C = E.
这篇关于Prolog 绑定参数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!