Sunday, 5 June 2016

Haskell: Remove duplicate elements from list


ListUtil.hs
removeDuplicates :: (Eq a) => [a] -> [a]
removeDuplicates list = remDups list []

remDups :: (Eq a) => [a] -> [a] -> [a]
remDups [] _ = []
remDups (x:xs) list2
    | (x `elem` list2) = remDups xs list2
    | otherwise = x : remDups xs (x:list2)

*Main> :load ListUtil.hs
[1 of 1] Compiling Main             ( ListUtil.hs, interpreted )
Ok, modules loaded: Main.
*Main> 
*Main> removeDuplicates [2, 3, 5, 5, 3, 9]
[2,3,5,9]
*Main> 
*Main> removeDuplicates "Hello How are you"
"Helo waryu"
*Main> 
*Main> removeDuplicates []
[]
*Main> 
*Main> removeDuplicates ""
""
*Main>


Previous                                                 Next                                                 Home

No comments:

Post a Comment