I am studying haskell language , doing some practices. Now I am attempting to implement my own ‘index’ function , meaning it can return the index of the given element within a list, but now my version fails to run , as the following
index' n (s:x)
| s/=n = 1+index' x
| otherwise = 0
main = print(index' 3 [1,2,3,5,6,7,9])
However , if simplifying the argument into one and set the target number in the guard , as the following , it run.
index' (s:x)
| s/=3 = 1+index' x
| otherwise = 0
main = print(index' [1,2,3,5,6,7,9])
Comparing the two program , I can find what make the former fail . So I think there may be a elemental mistake in my understanding , and I need a help , please !
your first version does not compile (I guess that implies “not running” but please include this info the next time ).
The problem is that you need to pass n to index' in the recursive call:
index' n (s : x)
| s /= n = 1 + index' n x
| otherwise = 0
this should compile, run and work with your example.
Please note that both versions are partial (for example index' 9 [1,2,3] will run into an non-exhaustive pattern error at runtime) but I guess you’ll expect that.
thank you ! your suggestions are illuminating for me . I am a beginner but find the language is amazing . I will do more practices to understand more details .
The other replies already answered your question, but I have some advice on debugging.
I suggest adding a type signature so that the compiler can give you better advice. If it’s difficult to work out the type, you can look at the error message for a hint. In your example, you can add the following line to your code:
index' :: a-> [a] -> a3
But with this type signature, the error you get is still quite confusing. If you make the type more specific, it can make the error message more helpful. So a better choice of type signature for debugging would be: