Wednesday, October 31, 2007

Haskell Substring Function

Somewhere out there a programmer is wondering, "Why doesn't Haskell seem to have a substring function? Why is this brave new world of functional programming so harsh and cruel?" (Well, maybe not the second part.) The isInfixOf function in Data.List does what you want. It isn't called "substring" because it also works with other types besides String. (See also isPrefixOf, isSuffixOf.)

I haven't seen this mentioned in Haskell tutorials so I'm posting it here.

Prelude> :m +Data.List
Prelude Data.List> "bc" `isInfixOf` "abcd"
True
Prelude Data.List> "zz" `isInfixOf` "abcd"
False

2 comments:

Crafty Green Poet said...

I've just found your blog and enjoyed reading - you've got some excellent posts!

Unknown said...

Thanks! Glad you liked it.