1

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!

2 Answers 2

2

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.

Sign up to request clarification or add additional context in comments.

Comments

1

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)

1 Comment

Thank you very much! I was thinking something like this, a separate variable for counting) just did'nt know what that woud look like in haskell. I didn't really know the syntax for where so I will have to look into that properly.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.