请注意,将列表用于 set 并不是一个好主意:
myUnion xs ys = Data.List.foldr Data.Set.insert Data.Set.empty (xs ++ ys)
如果您对 uniq 值列表进行了排序,您可能希望使用展开器:
myUnions xs0 ys0 = unfoldr walk (xs0, ys0) where
walk ([], []) = Nothing
walk ([], (y:ys')) = Just (y, ([], ys'))
walk ((x:xs'), []) = Just (x, (xs', []))
walk (xs@(x:xs'), ys@(y:ys')) | x < y = Just (x, (xs', ys))
| x > y = Just (y, (xs, ys'))
| otherwise = Just (x, (xs', ys'))
但如果你仍然坚持:
myUnion xs ys = foldr myInsert [] (xs++ys) where
myInsert x zs = if x `elem` zs then zs else (x:zs)
-- this one expects that both lists have uniq items
-- and checks only elements from xs for presence in ys
myUnion xs ys = foldr myInsert ys xs where
myInsert x zs = if x `elem` ys then zs else (x:zs)
-- but this should be written differently I guess
myUnion xs ys = filter (`notElem` ys) xs ++ ys