将谓词应用于列表元素的Prolog映射过程
如何编写将谓词PredName(Arg, Res)应用于List元素的Prolog过程map(List, PredName, Result) ,并将map(List, PredName, Result)返回到Result列表中?
例如:
test(N,R) :- R is N*N. ?- map([3,5,-2], test, L). L = [9,25,4] ; no
这通常被称为maplist/3 ,是Prolog序言的一部分。 注意不同的参数顺序!
:- meta_predicate maplist(2, ?, ?). maplist(_C_2, [], []). maplist( C_2, [X|Xs], [Y|Ys]) :- call(C_2, X, Y), maplist( C_2, Xs, Ys).
不同的参数顺序允许您轻松地嵌套几个maplist-目标。
?- maplist(maplist(test),[[1,2],[3,4]],Rss). Rss = [[1,4],[9,16]].
maplist来自不同的arities,并且对应于函数式语言中的以下结构 ,但要求所有列表长度相同。 请注意,Prolog不具有zip / zipWith和unzip之间的不对称性。 一个目标maplist(C_3, Xs, Ys, Zs)包含了这两者,甚至提供了更多的一般用途。
-
maplist/2对应all -
maplist/3对应于map -
zipWithmaplist/4对应于zipWith但也是unzip -
zipWith3maplist/5对应于zipWith3和unzip3 - …