Sunday, 5 June 2016

Haskell: Check whether a String is prefix of other String


Data.List module provides isPrefixOf function, which takes two lists as arguments and return True, if list1 is prefix of list2.

Prelude> import Data.List
Prelude Data.List> 
Prelude Data.List> isPrefixOf [2, 3, 5] [2, 3, 5, 6]
True
Prelude Data.List> 
Prelude Data.List> isPrefixOf [2, 3, 5] [2, 3]
False
Prelude Data.List> 
Prelude Data.List> isPrefixOf "Good Morning" "Good Morning friend"
True
Prelude Data.List> 
Prelude Data.List> isPrefixOf "Good Morning" "Good"
False

Lets implement the same functionality.


PrefixUtil.hs
isPrefix :: Eq a => [a] -> [a] -> Bool
isPrefix [] [] = True
isPrefix [] _ = True
isPrefix _ [] = False
isPrefix (x:xs) (y:ys) = (x==y) && (isPrefix xs ys)


*Main> :load PrefixUtil.hs 
[1 of 1] Compiling Main             ( PrefixUtil.hs, interpreted )
Ok, modules loaded: Main.
*Main> 
*Main> isPrefix [2, 3, 5] [2, 3, 5, 6]
True
*Main> isPrefix [2, 3, 5] [2, 3]
False
*Main> isPrefix "" "Hello"
True
*Main> isPrefix "H" "Hello"
True
*Main> isPrefix "Hello World" "Hello"
False
*Main> isPrefix "Hello World" "Hello World"
True
*Main> isPrefix "Hello World a" "Hello World"
False
*Main> 


Previous                                                 Next                                                 Home

No comments:

Post a Comment