Saturday, 4 June 2016

Haskell: Find exact matches between two lists

Write a function that takes two lists and return total number of matches in the list (Both content and index wise).


matchData.hs
{- Return 1 if both x and y are equal, else 0-}
match x y
    | (x==y) = 1
    | otherwise = 0

{- Return number of matches in both the lists -}
countMatches [] [] = 0
countMatches (x:xs) [] = 0
countMatches [] (y:ys) = 0
countMatches (x:xs) (y:ys) = (match x y) + (countMatches xs ys)

*Main> :load matchData.hs
[1 of 1] Compiling Main             ( matchData.hs, interpreted )
Ok, modules loaded: Main.
*Main> 
*Main> countMatches ["abc", "def", "ghi", "ijk"] ["abc", "xyz", "ghi", "def"]
2
*Main> countMatches ["abc", "def", "ghi", "ijk"] ["abc", "xyz"]
1
*Main> countMatches ["abc", "def", "ghi", "ijk"] []
0
*Main> countMatches ["abc"] ["abc", "xyz"]
1
*Main> countMatches [] ["abc", "xyz"]
0
*Main> countMatches [] []
0
*Main>



Previous                                                 Next                                                 Home

No comments:

Post a Comment