prolog - Appending a list to a list of lists recursively -
the problem i'm trying solve follows:
i'm given sorted list must pair first , last items in list. must pair 2nd , (last-1) items in list until list either empty or 1 element remains. must return list of pairs.
the steps decided take problem first check if list's length greater 1. if wasn't, means have list of 0 or 1 elements.
then first , last items in given list, delete them list, pair them, , recursively call same predicate on new list. once i've gone way down 0/1 items, pop , append them return list.
the problem i'm having when try append pair l = [first,last]
return list, errors out. code listed below.
t
input list.
first/2
gets first item in list. pair/3
strips away info p1
, p2
, creates l = [p1,p2]
.
getmatches(t,k,returnlist) :- ( length(t,val), val > 1, first(t,p1), last(t, p2), delete(t,p1,g), delete(g,p2,h), pair(p1,p2,l), getmatches(h,k,returnlist), append(l,k,returnlist) ; first(t,_), k = [] ).
an example use: if t = [1, 2, 3, 4, 5]
returnlist = [[1,5], [2, 4]]
should hold.
getmatches(list, returnlist) :- % getmatches/2 getmatches(list, [], answer), reverse(answer, returnlist), !. getmatches(list, listans, listans) :- % getmatches/3 length(list, l), l < 2. getmatches([h | tail], list, ans) :- last(tail, last), delete(tail, last, newtail), append([[h, last]], list, newlist), getmatches(newtail, newlist, ans).
and
?- getmatches([1,2,3,4,5],x). x = [[1, 5], [2, 4]].
Comments
Post a Comment