Error in this implementation

In this lecture on Haskell programming, there is a fold implementation defined as follows:

fold :: (a -> b -> b) -> b  -> [a] -> b
fold f z []     = z
fold f z (x:xs) = f x (fold z f xs)

The idea is to use it to determine the amount, product, etc.

sum''     = fold (+) 0
product'' = fold (*) 1
length''  = fold addOne 0
 where addOne _ s = 1 + s

There seems to be an inversion between zand fwithin the recursion pattern: otherwise, how does it z f xsfit (a -> b -> b) -> b -> [a]?

In my opinion, the recursion pattern should be

fold f z (x:xs) = f x (fold f z xs)

However, soon in the lecture you can find the following statement:

fold f z [a,b,c] = a `f` (b `f` (c `f` z))

This reinforces the so-called mistake, so I suppose there should be a mistake in my head!

Doesn't that look like the following?

fold f z [a,b,c] = `f` a (`f` b (`f` c z))

Am I missing a point, or is it a double mistake in a lecture?

+4
source share
2

, z f : z f xs (a -> b -> b) -> b -> [a]?

, , GHC , fold :

Couldn't match expected type ‘a -> b -> b’ with actual type ‘b’
  ‘b’ is a rigid type variable bound by
      the type signature for fold :: (a -> b -> b) -> b -> [a] -> b
      at test.hs:1:9
...

:

fold f z [a,b,c] = a `f` (b `f` (c `f` z))

, , !

?

fold f z [a,b,c] = `f` a (`f` b (`f` c z))

. fold, . f :

fold f z [a,b,c] = a `f` (b `f` (c `f` z))

fold f z [a,b,c] = f a (f b (f c z))

, , , f , ​​ (+);

fold (+) 0 [1,2,3] = 1 + (2 + (3 + 0))

fold (+) 0 [1,2,3] = (+) 1 ((+) 2 ((+) 3 0))
+5

fold f z (x:xs) = f x (fold z f xs) fold f z (x:xs) = f x (fold f z xs).

, , ( )

f x y == x `f` y

a `f` (b `f` (c `f` z)) == f a (f b (f c z))) 
+2

All Articles