Search code examples
haskellaverageapplicativefunction-compositionpointfree

Haskell - How does this average function work?


I found this implementation of the average function:

avg :: [Int] -> Int
avg = div . sum <*> length

How does this work? I looked at the function that was produced as a result of div . sum:

(div . sum) :: (Integral a, Foldable t) => t a -> a -> a

I understand that, but I'm unable to tell how <*> length does the work.


Solution

  • <*> :: Applicative f => f (a -> b) -> f a -> f b is the sequential application function that works on an Applicative structure. For a function, this is implemented as [src]:

    instance Applicative ((->) r) where
        pure = const
        (<*>) f g x = f x (g x)
        liftA2 q f g x = q (f x) (g x)

    so f <*> g is short for \x -> f x (g x). This thus means that in the case of avg:

    avg = div . sum <*> length
    

    is equivalent to:

    avg x = (div . sum) x (length x)
    

    which is thus equivalent to:

    avg x = div (sum x) (length x)
    

    so it divides the sum x with length x.