Better termination for s(X)-sum

前端 未结 4 1197
一个人的身影
一个人的身影 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:21

    Ok, seems its over. The solution I was thinking of was:

    nat_nat_sum2(0, N,N).
    nat_nat_sum2(s(N), 0, s(N)).
    nat_nat_sum2(s(N), s(M), s(s(O))) :-
       nat_nat_sum2(N, M, O).
    

    But as I realize, that's just the same as @mat's one which is almost the same as @WillNess'es.

    Is this really the better nat_nat_sum/3? The original's runtime is independent of B (if we ignore one (1) occurs check for the moment).

    There is another downside of my solution compared to @mat's solution which naturally extends to nat_nat_nat_sum/3

    nat_nat_nat_sum(0, B, C, D) :-
       nat_nat_sum(B, C, D).
    nat_nat_nat_sum(s(A), B, C, s(D)) :-
       nat_nat_nat_sum2(B, C, A, D).
    

    Which gives

    nat_nat_nat_sum(A,B,C,D)terminates_if b(A),b(B);b(A),b(C);b(B),b(C);b(D).
    

    (provable in the unfolded version with cTI)

提交回复
热议问题