[Haskell-cafe] Re: Function to find a substring

Paul R paul.r.ml at gmail.com
Tue Jun 8 11:08:44 EDT 2010

>>> What's an elegant definition of a Haskell function that takes two strings
>>> and returns "Nothing" in case the first string isn't a substring of the
>>> first, or "Just i", where i is the index number of the position within the
>>> first string where the second string begins?

my quick take, with Maybe and fmap :

substringP :: String -> String -> Maybe Int
substringP _ []  = Nothing
substringP sub str = case isPrefixOf sub str of
  False -> fmap (+1) $ substringP sub (tail str)
  True  -> Just 0


More information about the Haskell-Cafe mailing list