开发者

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

开发者 https://www.devze.com 2023-04-02 01:48 出处:网络
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

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

精彩评论

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