Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Prolog - return second to last list element

Tags:

prolog

puzzling over a problem of trying to return the second to last element in a list written in Prolog. This language is interesting to use but I'm having trouble getting my head wrapped around it. Here is what I have:

secondLast([X], X).
secondLast(X, [Y], X) :- secondLast(Y, K).    
secondLast(X, [Y|Z], K) :- secondLast(Y, Z, K).   
secondLast([X|Z], Ans) :- secondLast(X, Z, Ans).

so calling secondLast([a, b, c, d], X). X should equal c.

Any ideas?

Thanks!

like image 636
Mike D Avatar asked Jun 16 '26 22:06

Mike D


2 Answers

you should apply pattern matching:

secondLast([X,_], X).
secondLast([_|T], X) :- secondLast(T, X).
like image 100
CapelliC Avatar answered Jun 19 '26 20:06

CapelliC


Can be just:

secondLast(L, X) :-
    append(_, [X, _], L).
like image 28
Sergii Dymchenko Avatar answered Jun 19 '26 19:06

Sergii Dymchenko



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!