如何括号工作?(How do parenthesis work?)

2019-10-17 03:57发布

我写了一个算法,并试图实现它在Prolog的,但我发现了什么是预期括号不起作用:什么是写在不退出括号之前全部完成。 下面是代码:

%1. If the first member of L1 is smaller than L2
%     A. If the first member of L1 is not equal to Last
%            Than: A.1 Add the first member of L1 to the first member of NL
%                  Begin recurssion on the resumption of L1, L2 resumption of NL
%                  and Last from L1.
%            Else: A.2  begin the recursion on resumption of L1, L2 with the
%                       first member and L3 with the first member.
%  2. If the first member in L1 is equal to the first member of L2,
%             Than: Start recursion on resumption of L1 and L2 (with its first
%                   member) and Last = *.
%  3. If the first member of L1 is bigger than the first membber of L2
%             Than: begin recursion on L1 with the first member, resumption of
%             L2 and Last = x. %(x != * only for debugging)
%  

                              */
make_list([X1|L1], [X2|L2], [X3|NewL], Last) :-
    (
        X1 < X2,
        (
            X1 \= Last,   %A
            X3=X1;
            make_list(L1, [X2|L2], NewL, X1) %B
        ),  %Why those parenthesis do not work as expected?

        ! %green cut
    );
    (
        X1=X2,
        make_list(L1, [X2|L2], [X3|NewL], *)
    ),
    !
    ;
    make_list([X1|L1], L2, [X3|NewL], *).

我的问题是如何使它按预期工作?为什么B一度无法正常工作A做? 毕竟这也是在同一个括号,例如:

?- make_list([6,6,10,20],[10,25,30],L, -).
L = [6|_G849]  % (should be [6,20]).

EDIT1:make_list应该可以发现所有成员L1不在L2并把他们的NewL,而Last卖场中的最后一个成员L1是被解析。

EDIT2:无 - >允许(这是howmework)。 如果有人能告诉我该如何表达,如果再在别的序言,这可能是巨大的。

Answer 1:

总之: !/0适用于谓词级别:在这里,你会希望它适用于那些块将被分隔一些块级() 。 这适用于块切割的概念不存在序言。 一个切口将删除所有遇到的选择点,直到它在谓词的位置。

而不是用大量的编写代码(;)/2的使用,考虑引入新的条款相反,可读性(恰恰是因为我们不喜欢括号和搞清楚(;)/2(,)/2的优先级):

c :- A; B.

可以写成

c :- A.
c :- B.

这将经常是这样更好。 更容易制造代码,更好地维护它,阅读它,并展开它。

我没有看在深度或任何你的谓语,只是想提这两件事情。



Answer 2:

我怀疑你的“绿色切”是不是绿色可言; 你有

( A ; B ), !

所以从出口(A ; B)第一次,如果A成功, B将不再尝试-这就是切! 在这里说:不要尝试了。

如果你想B进行过尝试,取出切成!

IF-THEN-ELSE是:

ifte(A,B,C):- A, B.
ifte(A,B,C):- \+A, C.

我们可以饶了我们一个not使用cut

ifte(A,B,C):- A, !, B.
ifte(A,B,C):- C.

关于你的代码:我们表达and then用逗号: A,B 。 要输出的最后它是最容易使用的一个工作谓词,用另外的说法,“看到,最后”; 而在基本情况终于在最后出现,输出将被统一。



文章来源: How do parenthesis work?
标签: prolog