Search code examples
haskelloperatorsdecimal-pointfunction-composition

How does `sum (replicate 5 (max 6.7 8.9))` and `(sum . replicate 5 . max 6.7) 8.9` get the same result?


Rewrite (sum . replicate 5 . max 6.7) 8.9 using function composition. We have

(sum . replicate 5 . max 6.7) 8.9

I understand the part (sum . replicate 5 . max 6.7). But then how does it deal with 8.9?

edit from comments: turns out, the . in 6.7 is not a function composition operator, but a decimal dot!


Solution

  • If you write f . g, this is basically short for \x -> f (g x). Since the (.) operator is right associative your function is equivalent to:

    =    (sum . replicate 5 . max 6.7) 8.9
    --------------------------------------
       (sum . (replicate 5 . max 6.7)) 8.9
    

    and:

    =                    (sum . (replicate 5 . max 6.7)) 8.9
    --------------------------------------------------------
       (\x -> sum ((\y -> (replicate 5 (max 6.7 y))) x)) 8.9
    

    So now if we perform evaluation, we see:

    =  (\x -> sum ((\y -> (replicate 5 (max 6.7 y))) x)) 8.9
    --------------------------------------------------------
                 sum ((\y -> (replicate 5 (max 6.7 y))) 8.9)
    

    and:

    =  sum ((\y -> (replicate 5 (max 6.7 y))) 8.9)
    ----------------------------------------------
                   sum (replicate 5 (max 6.7 8.9))
    

    So the function composition will first place the 8.9 as second parameter of the max, and then apply all other functions to the result in some sort of chain from right-to-left.