Using an accumulator, "iterating"...

Artie Gold agold@bga.com
Fri, 20 Jun 2003 20:41:31 -0500


Brett Kelly wrote:
> Hello all,
> 
> I'm trying to write a function that takes a list and a element (same type) and
> returns the index of the first instance of the element in the list.  like:
> getindex "brett" 'e' would return 2, etc.
> 
> i'm trying to accomplish this using an accumulator, here's what i've got:
> 
> pyindex :: Eq a => a -> [a] -> Maybe Int
> pyindex c l = pyindex' 0 chr (x:xs)
>     where pyindex' count chr (x:xs) = do
>         if x == chr 
>           then return count
>           else pyindex' (count + 1) chr xs
> 
> now, i know i've got a syntax problem, because i'm pretty sure my logic is
> correct (or at least MOSTLY correct).
> 
> can anybody see what's wrong with my stuff?
> 
Sure.
Three comments:

1) You don't need (or want) the `do' -- that's used for dealing with 
monads.

2) The function's signature indicates a return type of `Maybe Int', yet 
you're trying to return an Int.

3) What if you _don't_ find the target?

Additional comments:

The `if...then...else' form may not be the clearest way -- or the most 
`Haskell-ish' way of expressing this computation.

You may want to look through the standard prelude to find how things 
like this are usually done.

Good luck and HTH,
--ag
-- 
Artie Gold -- Austin, Texas