prolog - How to construct "chained" lists of length n -


how generalise following statements construct chained list l of length n.

list(1,s1,s2,l) :-   l = [[s1,s2]]]. list(2,s1,s2,l) :-   l = [[s1,s3]],[s3,s2]]]. list(3,s1,s2,l) :-   l = [[s1,s3]],[s3,s4]],[s4,s2]]]. list(4,s1,s2,l) :-   l = [[s1,s3]],[s3,s4]],[s4,s5]],[s5,s2]]]. list(5,s1,s2,l) :-   l = [[s1,s3]],[s3,s4]],[s4,s5]],[s5,s6],[s6,s2]]]. 

what about:

chain(n, s0, s, ls) :-     length(ls, n),     chain_(ls, s0, s).  chain_([], s, s). chain_([[s0,s1]|ls], s0, s) :-     chain_(ls, s1, s). 

or equivalently, using foldl/4:

chain(n, s0, s, ls) :-     length(ls, n),     foldl(chain_, ls, s0, s).  chain_([s0,s], s0, s). 

example query:

?-  chain(3, s0, s, ls). ls = [[s0, _g1584], [_g1584, _g1593], [_g1593, s]]. 

Comments

Popular posts from this blog

javascript - Jquery show_hide, what to add in order to make the page scroll to the bottom of the hidden field once button is clicked -

python - Django-cities exits with "killed" -

python - How to get a widget position inside it's layout in Kivy? -