Sunday, 5 June 2016

Haskell: Implement list difference

If xs, ys are two lists then 'listDiff xs ys' removes the first occurrence of each element of ys in turn (if any) has been removed from xs.


ListUtil.hs
listDiff :: (Eq a) => [a] -> [a] -> [a]
listDiff xs [] = xs
listDiff xs (y:ys)
    | (y `elem` xs) = listDiff (deleteEle y xs) ys
    | otherwise = listDiff xs ys

deleteEle:: Eq a => a -> [a] -> [a]
deleteEle _ [] = []
deleteEle ele (x:xs)
    | (ele==x) = xs
    | otherwise = x : deleteEle ele xs

*Main> :load ListUtil.hs
[1 of 1] Compiling Main             ( ListUtil.hs, interpreted )
Ok, modules loaded: Main.
*Main> 
*Main> listDiff [2, 3, 4, 5] [3, 4, 10, 3, 4]
[2,5]
*Main> listDiff [2, 3, 4, 5] [2, 3, 4, 5]
[]
*Main> listDiff [2, 3, 4, 5, 3] [2, 3, 4, 5]
[3]
*Main> listDiff [2, 3, 4, 5, 3, 4] [2, 3, 4, 5]
[3,4]



Previous                                                 Next                                                 Home

No comments:

Post a Comment