r/prolog • • Jan 22 '19

[Beginner] append in a recursion.

I want a program that puts the last N items in a list,

So far I have;

returnN(S,[Head|Tail]):-

reverse([Head|Tail],[Head2|Tail2]),

delete_last([Head|Tail],X),

%append in new List Goes here

M is S-1,

returnN(M,X).

Head2 contains the element I want to concatenate with a list throughout each iteration of the recursion. I cant do append([Head2],[L],L). because L is empty in the first iteration. I would appreciate any help, thanks :)

0 Upvotes

3 comments sorted by

4

u/[deleted] Jan 22 '19

I was about to help but then I realized I have no freakin idea what it is you are trying to achieve.

1

u/playingwithunicorns Jan 22 '19

Hahha I'm sorry, the problem I'm trying to solve is, returning the last n elements of a list into a new list. I'm stuck because I can't figure out how to append the variable Head2 into a new list.

4

u/[deleted] Jan 22 '19 edited Jan 22 '19

Just use: length(Suffix, N), append(_, Suffix, List) where N is the number of last elements and List is the original list. For example, "last 3 elements of list [a,b,c,d,e,f]" is:

?- length(X, 3), append(_, X, [a,b,c,d,e,f]).
X = [d, e, f] .