[Haskell-cafe] Function to find a substring

Tillmann Rendel rendel at informatik.uni-marburg.de
Tue Jun 8 07:23:16 EDT 2010


Hi,

R J wrote:
> 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?

The naive algorithm of matching the second string on every position of 
the first string can be implemented as follows.

   import Data.List (findIndex, tails)

   findSubstringIndex text pattern
     = findIndex (pattern `isPrefixOf`) (tails text)

Tillmann


More information about the Haskell-Cafe mailing list