Prolog Recursion in lists, last but one element

前端 未结 6 672
闹比i
闹比i 2020-12-21 02:36

The question is to find the last but one character in a list, e.g.

?- last_but_one(X, [a,b,c,d]).
X = c.

My code is:

last         


        
6条回答
  •  遥遥无期
    2020-12-21 03:02

    I would say both answers are just as good and I would probably have written it the way you did. What they do in the second solution is that they check, before the recursive call, that the second element is not a empty list ([]). If you trace the two different solutions on the following query: last_but_one(X,[b]).

    You'll see that both give the same answer (false), but the second solution takes shorter amount of steps since it returns false before the recursive call is made.

提交回复
热议问题