Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
444 views
in Technique[技术] by (71.8m points)

map function - Prolog map procedure that applies predicate to list elements

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?

For example:

test(N,R) :- R is N*N.

?- map([3,5,-2], test, L).
L = [9,25,4] ;
no
question from:https://stackoverflow.com/questions/6682987/prolog-map-procedure-that-applies-predicate-to-list-elements

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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).

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 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 corresponds to all
  • maplist/3 corresponds to map
  • maplist/4 corresponds to zipWith but also unzip
  • maplist/5 corresponds to zipWith3 and unzip3
  • ...

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...