Using an accumulator, "iterating"...
Sat, 21 Jun 2003 17:22:05 +0100
Artie Gold 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)
> > 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?
> Three comments:
> 1) You don't need (or want) the `do' -- that's used for dealing with
> 2) The function's signature indicates a return type of `Maybe Int', yet
> you're trying to return an Int.
Maybe *is* a monad:
instance Monad Maybe where
Just x >>= k = k x
Nothing >>= k = Nothing
return = Just
fail s = Nothing
Having said that, treating it as such doesn't really have any benefit
Glynn Clements <email@example.com>