Using an accumulator, "iterating"...

Wolfgang Jeltsch wolfgang@jeltsch.net
Sat, 21 Jun 2003 14:33:51 +0200


On Saturday, 2003-06-21, 03:23, CEST, 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?
>
> thanks!

Hello,

I think, the following code, which uses certain prelude functions, would be 
clearer and more elegant:
    pyindex :: Eq a => a -> [a] -> Maybe Int
    pyindex c l = lookup c (zip l [0 ..])
I would it generally consider better style to not do recursion explicitely but 
use the recursion already provided by predefined functions like lookup.

Wolfgang