Prolog: Doubling the value of each element in a list of lists and returning a single list -
i need write set of clauses take list of integer lists , return single list elements doubled.
for example:
?- double([[1,2],[3]], x). yes x = [2,4,6]
i have set of clauses called mega_append return single list list of lists.
for example:
?- mega_append([[1,2],[3]], x). yes x = [1,2,3]
here progress (m_a short mega_append):
double([],[]). double(list,[h1|t1]) :- m_a(list,[h2|t2]), h1 2 * h2, double(t2, t1).
i'll try explain how thought work. flatten first list , split head , tail (h2 , t2). split second list head , tail (h1 , t1). check make sure h1 (the doubled value) equal 2 times h2 (the original value). if check rest of list. if match correctly should left 2 empty lists should match first clause , return yes.
it works when there single value (for example: double([[1]], x)
). can offer insight doing wrong? logic or code incorrect?
your problem t2 single list list after recursive call not list of lists.
to solve can first use mega_append flatten list , use auxiliary predicate work on flattened list. i.e. double this:
double([],[]). double(list,x) :- m_a(list,flist), double_aux(list, flist).
edit: here way use 1 clause since want see one. recommend using auxiliary predicate.
double([],[]). double([[]],[]). double(list,[h1|t1]) :- mega_append(list,[h2|t2]), h1 2 * h2, double([t2], t1).
Comments
Post a Comment