Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Understanding foldr's definition

Tags:

haskell

The definition of foldr is (according to https://hackage.haskell.org/package/base-4.12.0.0/docs/src/GHC.Base.html#local-6989586621679020249)

foldr            :: (a -> b -> b) -> b -> [a] -> b

That means the first argument is of type (a -> b -> b), the second b, the third [a] and returns b.

If we look at an example:

foldr (-) 54 [10, 11]

Doesn't - take two of the same type, and returns the same type? So shouldn't it be (a -> a -> a)?

like image 993
SilentDev Avatar asked Feb 06 '26 09:02

SilentDev


1 Answers

The fact that the signature of the function is a -> b -> b does not mean that a and b should be different types. It means a and b can be different types.

If you for example use (-) :: Num c => c -> c -> c, then Haskell will deduce that:

foldr ::          (a -> b -> b) -> (b -> ([a] -> b))
(-)      Num c =>  c -> c -> c
----------------------------------------------------
a ~ c, b ~ c

So a and b and c are thus the same type here. The type of foldr (-) thus has type:

foldr (-) :: Num c => c -> ([c] -> c)

foldr (-) thus takes a number of type c, and returns a function that maps a list of cs to a c.

like image 85
Willem Van Onsem Avatar answered Feb 09 '26 09:02

Willem Van Onsem