0

So I've got an assignment to Write a function

search_string:: String -> String -> Integer
search_string mainstring substring = ...

that takes two string arguments mainstring and substring and examines if substring occurs as a substring of mainstring. If so, the function should compute the position in mainstring where substring starts. If substring occurs multiple times it is the position of the first occurrence that should be computed. If substring does not occur in mainstring the function should compute -1.

So this is my code so far:

search_string main sub = if sub == take (length sub) main then 0 else search_string_aux main sub 1
search_string_aux main sub n = if sub == search_string (drop n main) sub then n else search_string_aux main sub (n+1)

when I try to load it haskell tells me:

Labb4hs:11:79:
  Couldn't match expected type '[a0]' with actual type 'Int'
  In the expression : n 
  In the expression:
   If sub == search_string (drop n main) sub then n
   else search_string_aux main sub (n+1)
  In an equation for `search_string_aux':
   search_string_aux main sub n = if sub == search_string (drop n main) sub then n 
   else search_string_aux main sub (n+1) 

So it seems Haskell thinks that n should be a [a0] =(string ???) with actual type Int, and I want to make n an Int always so I don't get why haskell thinks it's a [a0]. Would gladly appreciate some help since I'm new to Haskell and programming in general and I have no clue whatsoever on how to fix it.

3
  • 1
    You have an assignment to use -1 for "no match"? This function should give a Maybe Integer. This is not C. Commented Nov 13, 2014 at 18:26
  • yeah I have no idea why they want the function to return -1 if it doesn't match but they do so not much more to it. However I got it to work so no worries my :) Commented Nov 13, 2014 at 23:42
  • This is highly suspect... Commented Nov 14, 2014 at 23:42

1 Answer 1

3
  1. Try adding a type signature to search_string_aux. This will make the error a bit easier to find.

  2. if sub == search_string ...but wait, doesn't search_string return Integer? Yet sub is meant to be String... Something is not right here.

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

2 Comments

you got a good point there I can't have sub == search_strig .. I want it to always check some version of main
I got it to work!!! :D wiii so happy atm thx for noticing that error cause I was soooo blind to it have been working on the code for a long time makes you not see certain things

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.