Using an accumulator, "iterating"...

Glynn Clements glynn.clements@virgin.net
Sat, 21 Jun 2003 02:46:09 +0100


Brett Kelly wrote:

> 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)

None of chr, x or xs are defined here; if you change the above line
to:

	pyindex c l = pyindex' 0 c l

it works.

Except that you will get a match failure if the list doesn't contain
the specified element, so you also need a base case:

	pyindex' _ _ [] = Nothing

-- 
Glynn Clements <glynn.clements@virgin.net>