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

Francesco Ariis fa-ml at ariis.it
Sat Jan 16 22:35:55 UTC 2021


Il 16 gennaio 2021 alle 16:10 Lawrence Bottorff ha scritto:
> I have this
> 
> myLength1 = foldl (\n _ -> n + 1) 0
> 
> and this
> 
> myLength2 = foldr (\_ n -> n + 1) 0
> 
> I am guessing that foldl knows to assign the accumulator-seed argument to
> the dependent variable and the list argument's elements recursively to the
> independent variable; and with foldr to do the opposite. Is this a fair
> assumption? BTW, where can I get a look at the code for fold functions; or
> does the type definition answer my original question? Not really able to
> decipher it so well
> 
>  :t foldl
> foldl :: Foldable t => (b -> a -> b) -> b -> t a -> b

foldl and foldr have slightly different signatures,

    λ> :t +d foldl
    foldl :: (b -> a -> b) -> b -> [a] -> b
    λ> :t +d foldr
    foldr :: (a -> b -> b) -> b -> [a] -> b

(Notice  `b -> a -> b`  vs.  `a -> b -> b`), hence the lambdas have a
different non-matched parameter.
Does this answer your question? —F


More information about the Beginners mailing list