问题描述
你如何编写一个 Prolog 过程 map(List, PredName, Result)
将谓词 PredName(Arg, Res)
应用到 List 的元素
,并返回列表中的结果Result
?
How do you write a Prolog procedure map(List, PredName, Result)
that applies the predicate PredName(Arg, Res)
to the elements of List
, and returns the result in the list Result
?
例如:
test(N,R) :- R is N*N.
?- map([3,5,-2], test, L).
L = [9,25,4] ;
no
推荐答案
这通常称为 maplist/3
并且是 序言序言.注意不同的参数顺序!
This is usually called maplist/3
and is part of the Prolog prologue. Note the different argument order!
:- 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
目标.
The different argument order permits you to easily nest several maplist
-goals.
?- maplist(maplist(test),[[1,2],[3,4]],Rss).
Rss = [[1,4],[9,16]].
maplist
有不同的参数,对应于 以下是函数式语言中的结构,但要求所有列表的长度相同.请注意,Prolog 没有 zip
/zipWith
和 unzip
之间的不对称性.目标 maplist(C_3, Xs, Ys, Zs)
包含两者,甚至提供更通用的用途.
maplist
comes in different arities and corresponds to the following constructs in functional languages, but requires that all lists are of same length. Note that Prolog does not have the asymmetry between zip
/zipWith
and unzip
. A goal maplist(C_3, Xs, Ys, Zs)
subsumes both and even offers more general uses.
maplist/2
对应于all
maplist/3
对应于map
maplist/4
对应于zipWith
但也对应于unzip
maplist/5
对应于zipWith3
和unzip3
- ...
maplist/2
corresponds toall
maplist/3
corresponds tomap
maplist/4
corresponds tozipWith
but alsounzip
maplist/5
corresponds tozipWith3
andunzip3
- ...
这篇关于将谓词应用于列表元素的 Prolog 映射过程的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!