将谓词应用于列表元素的 Prolog 映射过程 [英] Prolog map procedure that applies predicate to list elements

查看:63
本文介绍了将谓词应用于列表元素的 Prolog 映射过程的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

你如何编写一个 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/zipWithunzip 之间的不对称性.目标 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 对应于 zipWith3unzip3
  • ...
  • 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
  • ...

这篇关于将谓词应用于列表元素的 Prolog 映射过程的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆