Skip to main content
3 of 6
added 132 characters in body
user avatar
user avatar

1+whatIndex p as will go through all of the remaining list and count them, it won't give you the index. Just use an iterative recursive helper function like this...

You can use either a local function, or the lifted version, which is what I have here.

whatIndex' :: (Eq a) => Integer -> a -> [a] -> Integer whatIndex' _ _ [] = -1 whatIndex' i p (x:xs) | p == x = i | otherwise = whatIndex' (i+1) p xs whatIndex p xs = whatIndex' 0 p xs main = print $ whatIndex 'a' "bbbbaccc" 

Here's a non tail-recursive version:

whatIndex _ [] = -1 whatIndex p (x:xs) | p == x = 0 | otherwise = 1 + whatIndex p xs 

Tail recursion refers to a class of recursive functions where the "last" or "final" function call in a recursive function is to the function itself. So that means that the function is not calling some other function (like +) in the "tail position" (the last place where a function call takes place). You can clearly see that the final function that is called in the first version of whatIndex is whatIndex whereas the final function that is called in the second version (with a call to whatIndex as a parameter) is +.

http://en.wikipedia.org/wiki/Tail_call

user903589