[Haskell-beginners] Are these soloutions all valid and a good use of Haskell

Stefan Höck efasckenoth at gmail.com
Mon Nov 10 20:15:12 UTC 2014

> I understand the theory but i loose it on the implementation.
> Lets take the better variant.
> last5 :: [a] -> Maybe a
>   last5 = foldr acc Nothing where
>       acc x Nothing  = Just x
>       acc _ j        = j
> Let's say we have [1,2,3]
> Do I understand that acc = Nothing. and x = 3 ?

Not, acc is not Nothing. acc is a function of type (a -> Maybe a ->
Maybe a). Nothing is a value of type Maybe a. The two cannot
possibly be the same.
foldr takes care of feeding the proper arguments to `acc`.

> and after  acc x Nothing = Just x  acc get's the value 3

The result of calling `acc` with arguments 3 and Nothing is `Just 3`.
But that's NOT the value of `acc`. acc is still a function. Note that
there is no such thing as in-place mutation in Haskell, so you
cannot just change the value of `acc`. But the RESULT of calling
  acc 3 Nothing

is `Just 3`. This result is taken by foldr and passed again to `acc`
together with the next item in the list. This continues until
the list is exhausted and foldr returns the last result it got from
calling `acc`.

> But how does x get's the value 3 or does foldr takes care of that ?

foldr takes care of all that. foldr calls `acc` with the proper
arguments and does all the bookkeeping internally. There is actually
not much to bookkeep. Here's an implementation of foldr

  foldr :: (a -> b -> b) -> b -> [a] -> b
  foldr _ b []     = b
  foldr f b (a:as) = foldr f (f a b) as

So, no great bookkeeping, just plain recursion.


More information about the Beginners mailing list