Sunday, 5 June 2016

Haskell: Check whether an element is in the list or not


Haskell provides ‘elem’ function, which takes an element and a list of elements as arguments and return True if the element is in the list, else False.
*Main> elem 113 [1, 2, 3, 113, 114]
True
*Main> 
*Main> elem 11 [1, 2, 3, 113, 114]
False
*Main> 
*Main> elem 'o' "Good Morning"
True


You can use elem function in infix notation also.
*Main> 113 `elem` [1, 2, 3, 113, 114]
True
*Main> 
*Main> 11 `elem` [1, 2, 3, 113, 114]
False
*Main> 
*Main> 'o' `elem` "Good Morning"
True

Lets implement elem function.


SearchUtil.hs
isElemExist :: (Eq a) => a -> [a] -> Bool
isElemExist _ [] = False
isElemExist ele (x:xs)
    | (ele == x) = True
    | otherwise = isElemExist ele xs

*Main> :load SearchUtil.hs
[1 of 1] Compiling Main             ( SearchUtil.hs, interpreted )
Ok, modules loaded: Main.
*Main> 
*Main> isElemExist 113 [1, 2, 3, 113, 114]
True
*Main> 
*Main> isElemExist 11 [1, 2, 3, 113, 114]
False
*Main> 
*Main> isElemExist 'o' "Good Morning"
True
*Main> 
*Main> 


You can use isElemExist function in infix notation also.
*Main> 113 `isElemExist` [1, 2, 3, 113, 114]
True
*Main> 
*Main> 11 `isElemExist` [1, 2, 3, 113, 114]
False
*Main> 
*Main> 'o' `isElemExist` "Good Morning"
True
*Main> 



Previous                                                 Next                                                 Home

No comments:

Post a Comment