简体   繁体   中英

Static result in a recursive Haskell function?

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) | 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!

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.

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)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM