how write functional program union of 2 lists or sets?
it depends on language, generally, there'll recursive solution involving traversal of sets identifying shared elements.
e.g. in haskell on native data.set
type,
union :: ord => set -> set -> set union tip t2 = t2 union t1 tip = t1 union t1 t2 = hedgeunion (const lt) (const gt) t1 t2 hedgeunion _ _ t1 tip = t1 hedgeunion cmplo cmphi tip (bin _ x l r) = join x (filtergt cmplo l) (filterlt cmphi r) hedgeunion cmplo cmphi (bin _ x l r) t2 = join x (hedgeunion cmplo cmpx l (trim cmplo cmpx t2)) (hedgeunion cmpx cmphi r (trim cmpx cmphi t2)) cmpx y = compare x y
or more simply, lists:
unionby :: (a -> -> bool) -> [a] -> [a] -> [a] unionby eq xs ys = xs ++ foldl (flip (deleteby eq)) (nubby eq ys) xs
Comments
Post a Comment