[Haskell-cafe] generalized, tail-recursive left fold that can finish tne computation prematurely
Andres Löh
andres.loeh at gmail.com
Mon Feb 18 17:26:41 CET 2013
Hi.
> while playing with folds and trying to implement `!!` by folding, I came to
> the conclusion that:
>
> - `foldr` is unsuitable because it counts the elements from the end, while
> `!!` needs counting from the start (and it's not tail recursive).
What is the problem with the following definition using foldr?
> index :: Int -> [a] -> a
> index n xs =
> foldr
> (\ x r n -> if n == 0 then x else r (n - 1))
> (const (error $ "No such index"))
> xs
> n
Cheers,
Andres
More information about the Haskell-Cafe
mailing list