[Haskell-beginners] Are these soloutions all valid and a good use of Haskell
r.wobben at home.nl
Mon Nov 10 20:43:38 UTC 2014
I think my error in thinking is that most of the languages store values
in a variable,
But it seems that haskell do not use it in a fold
Stefan Höck schreef op 10-11-2014 21:15:
>> 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.
> Beginners mailing list
> Beginners at haskell.org
More information about the Beginners