Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there a better way to write a "string contains X" method?

Just stared using Haskell and realized (at far as I can tell) there is no direct way to check a string to see if it contains a smaller string. So I figured I'd just take a shot at it.

Essentially the idea was to check if the two strings were the same size and were equal. If the string being checked was longer, recursively lop of the head and run the check again until the string being checked was the same length.

The rest of the possibilities I used pattern matching to handle them. This is what I came up with:

stringExists "" wordToCheckAgainst = False
stringExists wordToCheckFor "" = False
stringExists wordToCheckFor wordToCheckAgainst | length wordToCheckAgainst < length wordToCheckFor = False
                                               | length wordToCheckAgainst == length wordToCheckFor = wordToCheckAgainst == wordToCheckFor
                                               | take (length wordToCheckFor) wordToCheckAgainst == wordToCheckFor = True
                                               | otherwise = stringExists wordToCheckFor (tail wordToCheckAgainst)
like image 937
Programmin Tool Avatar asked Sep 06 '25 13:09

Programmin Tool


2 Answers

If you search Hoogle for the signature of the function you're looking for (String -> String -> Bool) you should see isInfixOf among the top results.

like image 115
Tom Crockett Avatar answered Sep 10 '25 03:09

Tom Crockett


isInfixOf from Data.List will surely solve the problem, however in case of longer haystacks or perverse¹ needles you should consider more advanced string matching algorithms with a much better average and worst case complexity.


¹ Consider a really long string consisting only of a's and a needle with a lot of a's at the beginning and one b at the end.

like image 32
Jan Avatar answered Sep 10 '25 01:09

Jan