Sunday 5 June 2016

Haskell: Check whether a String is suffix of other String


Data.List module provides isSuffixOf function, which takes two lists as arguments and return True, if list1 is suffix of list2.
*Main> import Data.List
*Main Data.List> 
*Main Data.List> isSuffixOf "Hello" "Hello"
True
*Main Data.List> isSuffixOf "Hello" "Hello123"
False
*Main Data.List> isSuffixOf "Hello" "Hello123Hello"
True
*Main Data.List> isSuffixOf [] []
True
*Main Data.List> isSuffixOf [2, 3, 5, 7] [2, 3, 5, 7]
True
*Main Data.List> isSuffixOf [2, 3, 5, 7] [1, 0,2, 3, 5, 7]
True
*Main Data.List> isSuffixOf [2, 3, 5, 7] [1, 0,2, 3, 5, 7, 11]
False

You can use isSuffixOf function in infix notation also.
*Main Data.List> "Hello" `isSuffixOf` "Hello"
True
*Main Data.List> [] `isSuffixOf` []
True
*Main Data.List> [] `isSuffixOf` [1]
True
*Main Data.List> [2, 3, 5, 7] `isSuffixOf` [1, 0, 2, 3, 5, 7]
True
*Main Data.List> [2, 3, 5, 7] `isSuffixOf` [1, 0, 2, 3, 5, 7, 11]
False


Lets implements isSuffixof functionality in Haskell.


SuffixUtil.hs
isSuffix :: Eq a => [a] -> [a] -> Bool
isSuffix [] [] = True
isSuffix _ [] = False
isSuffix [] _ = True
isSuffix xs ys = isPrefix (reverse xs) (reverse ys)


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

Prelude> :load SuffixUtil.hs 
[1 of 1] Compiling Main             ( SuffixUtil.hs, interpreted )
Ok, modules loaded: Main.
*Main> 
*Main> isSuffix "Hello" "Hello"
True
*Main> isSuffix "Hello" "Hello123"
False
*Main> isSuffix "Hello" "Hello123Hello"
True
*Main> 
*Main> isSuffix [] []
True
*Main> isSuffix [2, 3, 5, 7] [2, 3, 5, 7]
True
*Main> isSuffix [2, 3, 5, 7] [1, 0,2, 3, 5, 7]
True
*Main> isSuffix [2, 3, 5, 7] [1, 0,2, 3, 5, 7, 11]
False
*Main> 



Previous                                                 Next                                                 Home

No comments:

Post a Comment