Prolog: splitting a list into two lists (unique items / duplicate items) -
i have been trying split given list 2 different lists: unique , duplicate. example, if have list [1, 1, 2, 3, 3, 4, 5]
want unique list [2, 4, 5]
, duplicate [1, 3]
. don't want 1's in list in duplicate list. need 1 of it. code have right now:
comparel([_|[]], unique, dup). comparel([x3,y3 | tail], [x3 | unique], dup) :- x3 =\= y3, comparel([y3 | tail], unique, dup). comparel([x3,y3 | tail], unique, [x3 | dup]) :- x3 = y3, skipdups(x3, tail, unique, dup). skipdups(_, [], unique, dup). skipdups(x3,[y3 | tail], unique, dup) :- x3 =\= y3, comparel([y3 | tail], unique, dup). skipdups(x3,[y3 | tail], unique, dup) :- x3 = y3, skipdups(x3, tail, unique, dup).
using example list given above if run comparel([1, 1, 2, 3, 3, 4, 5], unique, dup).
get:
unique = [2, 4|_g1954], dup = [1, 3|_g1948].
i can't figure out why towards end of both lists getting '_g1954
' , '_g1948
'. appreciated. thanks.
here solution, key take/4 consumes matching leading items, enabling easy testing of list ( [_|_]
matches list of @ least 1 element )
comparel([], [], []). comparel([x|xs], u, d) :- ( take(x, xs, [_|_], ys) -> comparel(ys, u, b), d = [x|b] ; comparel(xs, a, d), u = [x|a] ). take(x, [x|xs], [x|r], ys) :- !, take(x, xs, r, ys). take(_, ys, [], ys).
Comments
Post a Comment