DEV Community

Pan Chasinga
Pan Chasinga

Posted on

4 3

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.

Neon image

Serverless Postgres in 300ms (❗️)

10 free databases with autoscaling, scale-to-zero, and read replicas. Start building without infrastructure headaches. No credit card needed.

Try for Free →

Top comments (0)

Neon image

Next.js applications: Set up a Neon project in seconds

If you're starting a new project, Neon has got your databases covered. No credit cards. No trials. No getting in your way.

Get started →

👋 Kindness is contagious

Engage with a wealth of insights in this thoughtful article, cherished by the supportive DEV Community. Coders of every background are encouraged to bring their perspectives and bolster our collective wisdom.

A sincere “thank you” often brightens someone’s day—share yours in the comments below!

On DEV, the act of sharing knowledge eases our journey and forges stronger community ties. Found value in this? A quick thank-you to the author can make a world of difference.

Okay