Sunday, 5 June 2016

Haskell: implement intersection of two lists


listUtil.hs
intersect :: Eq a => [a] -> [a] -> [a]
intersect [] _ = []
intersect (x:xs) ys
    | x `elem` ys = x : intersect xs ys
    | otherwise = intersect xs ys

*Main> :load listUtil.hs
[1 of 1] Compiling Main             ( listUtil.hs, interpreted )
Ok, modules loaded: Main.
*Main> 
*Main> intersect [2, 3, 5, 2, 3, 7] [5, 7, 7, 10, 11]
[5,7]
*Main> 
*Main> intersect [2, 3, 5, 2, 3, 7] [5, 7, 7, 10, 11, 2, 3]
[2,3,5,2,3,7]
*Main> 
*Main> intersect [2, 3, 5, 2, 3, 7] []
[]
*Main> 
*Main> intersect [2, 3, 5, 2, 3, 7] [2]
[2,2]
*Main> intersect [2, 3, 5, 2, 3, 7] [2, 3]
[2,3,2,3]
*Main> 


Previous                                                 Next                                                 Home

No comments:

Post a Comment