user1010101
user1010101

Reputation: 1658

Merging lists with unique elements

I am trying to combine two lists and remove duplicates.Following is my code but i think i have syntax error and also can anyone suggest a better method to implement this as i am sure there is a better way.

MY CODE

combine :: [Int] -> [Int] -> [Int]

combine (x:xs++y:ys)
         |elem x xs || elem x ys = combine xs ++ ys
         |elem y xs || elem y ys = combine xs ++ ys
         |otherwise x:y:combine xs ys

I know what the problem wants me to do and i know how to solve it but i am not able to get over the syntax. Any help would be appreciated

Upvotes: 2

Views: 2555

Answers (1)

MushinNoShin
MushinNoShin

Reputation: 4886

The problem is you've defined the type of combine as taking two lists of ints and returning a list of ints, but you're defining combine as taking the combination of two lists. Also I believe otherwise requires the =

combine :: [Int] -> [Int] -> [Int]
combine x y
  | null x && not (null y) = y
  | null y && not (null x) = x
  | null x && null y = []
  | elem (head x) (tail x) || elem (head x) (tail y) = combine (tail x) y
  | elem (head y) (tail x) || elem (head y) (tail y) = combine x (tail y)
  | (head x) == (head y) = (head x) : combine (tail x) (tail y)
  | otherwise = (head x) : (head y) : combine (tail x) (tail y)

This just smells like there's better ways. There's probably performance gain somewhere (scanning lists multiple times with elem, I'm looking at you). This code also looks like it's doing a lot of repeating itself too.

A much easier way is by using the nub function in Data.List.

import Data.List { nub }
combine:: [Int] -> [Int] -> [Int]
combine x y = nub (x ++ y)

After a short cabal install data-ordlist:

import Data.List.Ordered
combine x y = nubSort $ x ++ y

which runs a lot faster. wee!

Upvotes: 2

Related Questions