[Haskell-beginners] Dependent and independent variables in foldl and foldr

Francesco Ariis fa-ml at ariis.it
Sun Jan 17 05:55:20 UTC 2021


Il 16 gennaio 2021 alle 23:32 Lawrence Bottorff ha scritto:
> This is the definition of list foldr
> 
> foldr            :: (a -> b -> b) -> b -> [a] -> b
> foldr _ z []     =  z
> foldr f z (x:xs) =  f x (foldr f z xs)
> 
> In both foldl and foldr in the OP the n variable in lambda functions would
> seem to be for the accumulator, hence, I assume the n is considered the
> free variable? And then the wildcard in each lambda function refers to the
> bound variable, i.e., the list argument's elements to be folded.

The ‘_’ means «do not bind this parameter». Hence

    λ> (\x _ -> x + 1) 10 20
    11

> but the second example I'm not sure how the (\x n -> x + n) is being
> applied in the form . . . f x (foldr f z xs) It obviously must be doing the
> same (+) 1 ((+) 2 ((+) 3 ((+) 4 5))) but how the function is being applied
> I don't understand.

    foldr (+) 0 ([1,2,3])
    (+) 1 (foldr (+) 0 [2,3])
    (+) 1 ((+) 2 (foldr (+) 0 [3]))
    (+) 1 ((+) 2 ((+) 3 (foldr (+) 0 [])))
    (+) 1 ((+) 2 ((+) 3 0))
    (+) 1 ((+) 2 3)
    (+) 1 5
    6

> BTW, is the t a format in
> 
> :type foldr
> foldr :: Foldable t => (a -> b -> b) -> b -> t a -> b
> 
> something from category theory, i.e., for the list instance, t a is [a] What
> is the algebraic syntax where t a becomes [a] in the case of lists? It
> would be nice to understand some day exactly what :i Foldable is saying

What book are you studying on that does not talk about Typeclasses?
I feel you are making your life harder by not following a good
study program.


More information about the Beginners mailing list