DEV Community

Pan Chasinga
Pan Chasinga

Posted on

Grokking Partial Application

If you started programming in an imperative language such as Java like I did, learning to grok functional programming can be a daunting endeavor.

What partial application, or known by some as "currying" after the late mathematician Haskell Curry, is applying a function to a value, which returns another function yet to be applied to another value.

Look at the following function in JavaScript:

const add = (a) => (b) => x + y
Enter fullscreen mode Exit fullscreen mode

As you first apply this function to the first number 9, it replaces a and returns the function (b) => 9 + b:

const addNine = add(9)
// -> (9) => (b) => 9 + n2
// -> (b) => 9 + n2
Enter fullscreen mode Exit fullscreen mode

We end up with a half-applied function addNine that, when applied to another number, will add it to number 9 which is being stored on the stack. In another word, the computation was being suspended until the next application.

This is indeed different from the following function:

const add = (a, b) => a + b
Enter fullscreen mode Exit fullscreen mode

If we partially applied this function to a single value 5,a would be substituted with a number while b will be undefined, resulting in an execution of 5 + undefined which equals to NaN, a very obscure result to ever be returned by a language.

Functions in functional languages such as Ocaml and Haskell are curried, which means they apply to each value at a time no matter how many parameters they have. Take these two Haskell functions, which are similar:

add1 :: Int -> Int -> Int
add1 a b = a + b

add2 :: Int -> Int -> Int
add2 a = \b -> a + b
Enter fullscreen mode Exit fullscreen mode

The line above each function's definition is the function's type declaration. They show that both functions are in fact the same—a two-step application process to the end value.

Top comments (0)