Better termination for s(X)-sum

前端 未结 4 1178
一个人的身影
一个人的身影 2020-12-11 17:55

(Let me sneak that in within the wave of midterm questions.)

A common definition for the sum of two natural numbers is nat_nat_sum/3:

na         


        
4条回答
  •  囚心锁ツ
    2020-12-11 18:41

    Take the following two definitions:

    Definition 1:

    add(n,X,X).
    add(s(X),Y,s(Z)) :- add(X,Y,Z).
    

    Definition 2:

    add(n,X,X).
    add(s(X),Y,Z) :- add(X,s(Y),Z).
    

    Definition 1 terminates for pattern add(-,-,+), whereas definition 2 does not terminate for pattern add(-,-,+). Look see:

    Definition 1:

    ?- add(X,Y,s(s(s(n)))).
    X = n,
    Y = s(s(s(n))) ;
    X = s(n),
    Y = s(s(n)) ;
    X = s(s(n)),
    Y = s(n) ;
    X = s(s(s(n))),
    Y = n
    ?- 
    

    Definition 2:

    ?- add(X,Y,s(s(s(n)))).
    X = n,
    Y = s(s(s(n))) ;
    X = s(n),
    Y = s(s(n)) ;
    X = s(s(n)),
    Y = s(n) ;
    X = s(s(s(n))),
    Y = n ;
    Error: Execution aborted since memory threshold exceeded.
        add/3
        add/3
    ?- 
    

    So I guess definition 1 is better than definition 2.

    Bye

提交回复
热议问题