Suppose I have a list [1,2,1,3,2,0,8,3,1]
,I wa开发者_运维问答nt to find the index of the last 3 which is 7
, How to do it in prolog?
Something like
last(List, Needle, Ret) :- last1(List, Needle, 0, -1, Ret).
last1([H | T], N, Idx, Acc, Ret) :- Idx2 is Idx + 1, (H == N, !, last1(T, N, Idx2, Idx, Ret); last1(T, N, Idx2, Acc, Ret)).
last1([], _, _, Acc, Acc).
This traverses the whole list, maintaining the index of the last needle seen. Is this homework?
精彩评论