Seb*_*wak 2 prolog meta-predicate
在 sicstus prolog 中,有一个谓词:
maplist(:Pred, +List)
Run Code Online (Sandbox Code Playgroud)
Pred
应该只采用一个参数 -List
元素。如何通过定义第一个参数的 2 参数谓词?在其他语言中,它会被写成:
maplist(pred.bind(SomeValue), List)
Run Code Online (Sandbox Code Playgroud)
maplist(P_1, Xs)
将调用call(P_1, X)
的每个元素Xs
。内置谓词call/2
向P_1
再添加一个参数,然后用 调用它call/1
。为了表明需要进一步的论点,使用P_1
“需要一个额外的论点”之类的名称是非常有帮助的。
因此,如果您已经有一个 arity 2 的谓词,例如(=)/2
,,您将传递=(2)
给 maplist:
?- maplist(=(2), Xs).
Xs = [] ;
Xs = [2] ;
Xs = [2,2] ...
Run Code Online (Sandbox Code Playgroud)
不幸的是,由于 SICStus 库中的定义不正确,请使用以下定义:
:- 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).
Run Code Online (Sandbox Code Playgroud)
有关更多信息,请参阅此答案。
只是关于列表列表的一个很好的进一步示例。
?- Xss = [[A],[B,C]], maplist(maplist(=(E)), Xss).
Xss = [[E], [E, E]],
A = B, B = C, C = E.
Run Code Online (Sandbox Code Playgroud)