Julia Language Closures Implementing Currying


One application of closures is to partially apply a function; that is, provide some arguments now and create a function that takes the remaining arguments. Currying is a specific form of partial application.

Let's start with the simple function curry(f, x) that will provide the first argument to a function, and expect additional arguments later. The definition is fairly straightforward:

curry(f, x) = (xs...) -> f(x, xs...)

Once again, we use anonymous function syntax, this time in combination with variadic argument syntax.

We can implement some basic functions in tacit (or point-free) style using this curry function.

julia> const double = curry(*, 2)
(::#19) (generic function with 1 method)

julia> double(10)

julia> const simon_says = curry(println, "Simon: ")
(::#19) (generic function with 1 method)

julia> simon_says("How are you?")
Simon: How are you?

Functions maintain the generism expected:

julia> simon_says("I have ", 3, " arguments.")
Simon: I have 3 arguments.

julia> double([1, 2, 3])
3-element Array{Int64,1}: