Writing list's first elements
Question
I try to write a prolog list's first two elements in recursion.. for example:
if i have
List:[a,b,c,d,e,f]
when i enter
first_two(F,S,List).
It returns
F:a, S:b ;
F:b, S:c ;
F:c, S:d ;
F:d, S:e ;
F:e, S:f .
I try to do this with:
first_two(F,S,[F|[S|Tail]]):-first_two(F,S,Tail).
but it fails..
Thank you very much..
Solution
you forgot the base case of recursion, i.e. the termination condition:
first_two(F, S, [F, S|_Tail]).
first_two(F, S, [_|Tail]) :-
first_two(F, S, Tail).
I've also simplified your rule, with friendly syntax and spacing.
I prefer simpler code to read, don't you?
OTHER TIPS
If all you want is the first two, then your solution is pretty close, but doesn't need the recursion:
first_two( F, S, [F|[S|_]] ).
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow