[Haskell-beginners] foldr for Nats
daniel.is.fischer at web.de
Tue Jan 26 06:23:06 EST 2010
Am Dienstag 26 Januar 2010 11:52:45 schrieb kane96 at gmx.de:
> I have:
> data Nat = Z | S Nat deriving (Eq,Ord,Show)
> and should write a function that works for Nats like foldr for list
> where: instance Enum Nat where
> toEnum i | i < 0 = error "foo"
> | i == 0 = Z
> | otherwise = S (toEnum (i-1))
> Can someone give me a hint how to do this?
I don't understand what "works for Nats like foldr for lists" means.
A very nice explanation of how foldr works is
foldr f z
(a1 : (a2 : (a3 : (... : (an : ) ...))))
~> (a1 `f` (a2 `f` (a3 `f` (... `f` (an `f` z) ...))))
So we replace the constructor  with the base value z, and the constructor
(:) with the function f.
Maybe it's meant to be similar, foldNat f z should replace the constructor
Z with the base value and the constructor S with the function.
More information about the Beginners