开发者

Prolog: find the last index of an element in a list

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?

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜