Prolog map procedure that applies predicate to list elements

后端 未结 1 776
礼貌的吻别
礼貌的吻别 2020-11-21 23:49

How do you write a Prolog procedure map(List, PredName, Result) that applies the predicate PredName(Arg, Res) to the elements of List,

1条回答
  •  遇见更好的自我
    2020-11-22 00:09

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

    0 讨论(0)
提交回复
热议问题