Should I avoid tail recursion in Prolog and in general?

前端 未结 5 1740
后悔当初
后悔当初 2020-12-02 01:49

I\'m working through \"Learn Prolog now\" online book for fun.

I\'m trying to write a predicate that goes through each member of a list and adds one to it, using acc

5条回答
  •  挽巷
    挽巷 (楼主)
    2020-12-02 02:23

    Your addOne procedure already is tail recursive.

    There are no choice points between the head and the last recursive call, because is/2 is deterministic.

    Accumulators are sometime added to allow tail recursion, the simpler example I can think of is reverse/2. Here is a naive reverse (nreverse/2), non tail recursive

    nreverse([], []).
    nreverse([X|Xs], R) :- nreverse(Xs, Rs), append(Rs, [X], R).
    

    if we add an accumulator

    reverse(L, R) :- reverse(L, [], R).
    reverse([], R, R).
    reverse([X|Xs], A, R) :- reverse(Xs, [X|A], R).
    

    now reverse/3 is tail recursive: the recursive call is the last one, and no choice point is left.

提交回复
热议问题