Prolog: comparing the respective elements in 2 lists

时间:2015-11-12 12:13:22

标签: list prolog clpb

I have 2 lists [x1, x2, ...xn] and [y1, y2, ...yn] of the form {0, 1}^n.

I want to generate a new list [a1, a2 ... an] such that ai = xi AND yi for every i from 1 to n (i.e., if x1 = y1 = 1 then a1 = 1 or if x1 = 1, y1 = 0, then a1 = 0)

How can I implement a predicate using recursion?

2 个答案:

答案 0 :(得分:3)

maplist/4Prolog lambdas一起使用,如下所示:

?- use_module([library(clpb),library(lambda)]).
true.

?- maplist(\A^B^AB^sat(A*B =:= AB),
           [1,1,0,0],
           [1,0,0,1],
           Products).
Products = [1,0,0,0].

答案 1 :(得分:0)

免责声明:这个答案只是后人comment by @lurker的更明确版本。

首先,你如何做AND?一个简单的选择是使用按位AND:

and(A, B, R) :- R is A /\ B.

现在,你想要的就是:

?- maplist(and, [1, 0, 0, 1], [0, 1, 0, 1], L).
L = [0, 0, 0, 1].

这是maplist是什么?由于SWI-Prolog的代码既可用又易于浏览,您可以查看standard library definition

maplist(Goal, List1, List2, List3) :-
    maplist_(List1, List2, List3, Goal).

maplist_([], [], [], _).
maplist_([Elem1|Tail1], [Elem2|Tail2], [Elem3|Tail3], Goal) :-
    call(Goal, Elem1, Elem2, Elem3),
    maplist_(Tail1, Tail2, Tail3, Goal).

这比您可能需要的更为通用。首先,您不需要将and/3传递给要编写的谓词,您可以简单地内联它。因此,您将call替换为and或仅替换为is。现在您也不需要重新排序参数,因此您不需要具有谓词和辅助谓词。

那里有很多代码,不看它并尝试学习是一种耻辱。

相关问题