Prolog unifying two lists -


alright, trying unify 2 lists: [2] , [1,_,3] giving answer of [1,2,3]. code below:

unify([],[],_). unify(list1, [head|rest], list2) :- member(list1,head),!,                                          unify([x|_], rest, [x|list2]). unify(list1, [head|rest], [head|list2]) :- unify(list1, rest, list2). 

when put ?-unify([2],[1,_,3],l) gives me false, want give l=[1,2,3]. how can improve above code?

i tried trace couldn't figure out.

[debug] 5 ?- unify([2],[1,_,3],l). t call: (6) unify([2], [1, _g512, 3], _g520) t redo: (6) unify([2], [1, _g512, 3], _g520) t call: (7) unify([2], [_g512, 3], _g602) t call: (8) unify([_g607|_g608], [3], [_g607|_g602]) t redo: (8) unify([_g607|_g608], [3], [_g607|_g602]) t call: (9) unify([3|_g608], [], _g602) t fail: (9) unify([3|_g608], [], _g602) t fail: (8) unify([_g607|_g608], [3], [_g607|_g602]) t fail: (7) unify([2], [_g512, 3], _g602) t fail: (6) unify([2], [1, _g512, 3], _g520) false 

first, need fix base case: rather using

unify([],[],_). 

which says empty list on left requires empty list in middle, , produces undefined result, use these two:

unify(_,[],[]). unify([],l,l). 

the first base clause says if second list empty, output empty well, no matter what's in first list.

the second base clause says when first list empty, output same second list.

now need build 2 clauses reduce problem:

unify([h|t1], [h|t2], [h|r]) :- unify(t1, t2, r). unify([h1|t1], [h2|t2], [h2|r]) :- h1 \= h2, unify([h1|t1], t2, r). 

the first clause says if heads of 2 lists unify, attach unified heads output of reduced problem when both lists reduced.

the second clause says if heads not unify, attach head of second list output of reduced problem when second list reduced.

here demo on ideone.


Comments

Popular posts from this blog

how to proxy from https to http with lighttpd -

android - Automated my builds -

python - Flask migration error -