Reputation: 11
I am a beginner in Haskell programming and have gotten an assignment to create a function that checks if a given string is the substring of another string and if it is it returns the position of the substring in the main string. This is what I have so far:
findString :: String -> String -> Integer
findString mainstring substring
| length substring > length mainstring = (-1)
| take (length substring) mainstring == substring = 0
| otherwise = 1 + findString (drop 1 mainstring) substring
The instructions for this assignment explicitly state that I have to use findString :: String -> String -> Integer
and that if the substring is not a substring of the mainstring it should return (-1)
. Right now the recursive part of the function interferes with the result of| length substring > length mainstring = (-1)
by adding +1
to it for each recursion but I just want a static (-1)
. I feel like I'm very close here but I've been stuck on this one for quite some time now. Any help would be appreciated!
Upvotes: 1
Views: 71
Reputation: 1533
Don't fix your thoughts on the type signatures, you can have define functions inside a function as well
findString :: String -> String -> Integer
findString mainstring substring = helper mainstring substring 0
where
helper mainstring substring len
| length substring > length mainstring = (-1)
| take (length substring) mainstring == substring = len
| otherwise = helper (drop 1 mainstring) substring (len + 1)
Upvotes: 1
Reputation: 170815
Instead of just doing otherwise = 1 + findString (drop 1 mainstring) substring
, compare the value with -1
first. Look up let
and where
in your study materials, they will help. I think that's enough given it's an assignment.
Upvotes: 2