Search code examples
haskellcompositionpartial-application

adding a value with composition and partial application haskell


I'm trying to write this function applying composition and partial application with Haskell:

function m n = (m^2) + n

I tried this with:

function m = (m^2).(+)

Solution

  • The problem with that approach is that (+) is a binary operator. Since you put it at the right of the dot ., it will not be applied to the left operand. So you have written:

    function :: Num a => a -> a -> a
    function m = (.) (m^2) (+)  -- wrong
    

    This is short for:

    function m = \n -> ((m^2) ((+) n))
    

    So that means that (+) n will result in a function (n+) and we will apply that function to the result of (m^2), which does not make much sense.

    You can however simply use:

    function :: Num a => a -> a -> a
    function m = (+) (m^2)
    

    Or:

    function :: Num a => a -> a -> a
    function m = ((m^2) +)
    

    Given function m = (+) (m^2), if we apply n on that function, we will obtain:

    ((+) (m^2)) n
    -> (+) (m^2) n
    -> (m^2) + n
    

    You can further modify the function and drop the m argument as well, with:

    function :: Num a => a -> a -> a
    function = (+) . (^ 2)
    

    Which is syntactical sugar for:

    function :: Num a => a -> a -> a
    function = (.) (+) (^2)
    

    If we now apply m on the function, it will evaluate to:

    ((.) (+) (^2)) m
    -> (\x -> (+) ((^2) x)) m
    -> (+) ((^2) m)
    -> (+) (m^2)
    

    So we obtain the state like in the previous command.