Prolog: get and append every third item from a list to a new list -
with following piece of code in prolog managed extract every third item list:
third([_,_,z|l], z). third([_,_,c|l], y) :- third(l, y).
however, still need append every item extracting new list, , create list "every third" items. appreciate hint or help! thank you.
how doing this?
list_thirds([] , []). list_thirds([_] , []). list_thirds([_,_] , []). list_thirds([_,_,e|es], [e|xs]) :- list_thirds(es, xs).
sample queries using sicstus prolog 4.3.2:
| ?- list_thirds([], xs). xs = [] ? ; no | ?- list_thirds([a,b,c], xs). xs = [c] ? ; no | ?- list_thirds([a,b,c,d,e,f], xs). xs = [c,f] ? ; no | ?- list_thirds([a,b,c,d,e,f,g], xs). xs = [c,f] ? ; no
how going "other direction"?
| ?- list_thirds(list, [x,y]). list = [_a,_b,x,_c,_d,y] ? ; list = [_a,_b,x,_c,_d,y,_e] ? ; list = [_a,_b,x,_c,_d,y,_e,_f] ? ; no % terminates universally
last, @ answer sequence general query:
| ?- list_thirds(es, xs). es = [] , xs = [] ? ; es = [_a] , xs = [] ? ; es = [_a,_b] , xs = [] ? ; es = [_a,_b,_c] , xs = [_c] ? ; es = [_a,_b,_c,_d] , xs = [_c] ? ; es = [_a,_b,_c,_d,_e] , xs = [_c] ? ; es = [_a,_b,_c,_d,_e,_f], xs = [_c,_f] ? ; ...
Comments
Post a Comment