Update, August 5, 2020: Swift has changed a lot since this article was first published in 2014. Most of the code snippets have been tweaked in order to compile under more recent Swift compilers. Where it didn’t make sense to tweak the code, the differences between then and now have been explained, along with links to the relevant Swift Evolution proposals where possible. Enjoy!
—Adam
There’s a chance you’ve heard a term floating around with some of the more functional-minded languages. The term is “curry” and not only is it a delicious Southeastern Asian cuisine, it also refers to translating the evaluation of a function that takes multiple arguments into evaluating a sequence of functions, each with a single argument. Obviously.
Let’s take a quick walk through the world of function currying in Swift, figure out what that nonsense above really means, and then see how we could use this technique in the real world.
No seriously though, what is currying
Let’s work our way up. Here’s a normal function in Swift that takes two Int
s
as arguments, a
and b
, then adds them together:
func add(_ a: Int, _ b: Int) -> Int {
return a + b
}
So now, if we want to use this function, we can call it:
let sum = add(2, 3) // sum = 5
This is useful. But what if we wanted to take a list of numbers, and add 2 to
each one, getting a new list back. We could create a quick list of
numbers using a Range
, then use Range.map
to iterate through and get a new
list. That would give us a chance to apply add
to the integer 2
and each
number in the range:
let xs = 1...100
let x = xs.map { add($0, 2) } // x = [3, 4, 5, 6, etc]
That’s not horrible, but this is also a monumentally contrived example. It
feels weird to me to have to create a closure just for the sake of passing
add
with a default value. It could also get a little hairy if the function
was more complicated, and we needed to supply more default parameters.
Fortunately we can use function currying to help.
If we just look at types, we can see that add
has a type of (Int, Int) ->
Int
. So it takes 2 parameters of the type Int
, and returns an Int
.
However, what we really want is something to pass to map
, which takes a
function of the type (A) -> B
:
extension Range<A> {
func map<B>(_ transform: (A) -> B) -> [B]
}
Note that the above snippet doesn’t compile because you can’t create an extension on a generic type. The actual implementation is in the standard lib, and is only here for illustration purposes.
So, if we had a function that took one argument, and returned one value, we
wouldn’t need to use a closure for map
at all. Instead, we could pass the
function to map
directly. Well, we could make this work by wrapping add
in
a new function:
func addTwo(_ a: Int) -> Int {
return add(a, 2)
}
let xs = 1...100
let x = xs.map(addTwo) // x = [3, 4, 5, 6, etc]
But this feels a little too specific. What if we wanted to create addThree
or addOneHundred
. If we keep going down this road, we’d need to continue to
create wrapper functions for each integer we want to use. It would be nicer to
be able to build something that could be applied more generally for any
integer. We can do this by writing our functions to return other functions.
To illustrate this, let’s start by modifying that original method:
func add(_ a: Int) -> ((Int) -> Int) {
return { b in a + b }
}
We’ve now redefined our function as one that takes a single argument. The
return value is a function that takes a single argument and returns the sum of
a
(passed by name to the function), and b
(passed to, and named by, the
closure). This means two things:
- If we want to satisfy all of the arguments for the function and call it
immediately, we now need to separate the arguments with parenthesis:
let sum = add(2)(3) // sum = 5
- It also lets us “partially apply” the
add
function. This means that passing one argument toadd
returns a new function that accepts the next argument. Once that argument is satisfied, this new unnamed function finally returns the result.
What’s the benefit of this? Well, it allows us to create smaller functions
out of larger functions by reducing the number of arguments needed. Our
addTwo
function definition, for example, can easily become a simple let
:
let addTwo = add(2)
And now addTwo
is a function that takes a single Int
argument, and returns
an Int
, which means we can still pass it directly to map
:
let addTwo = add(2)
let xs = 1...100
let x = xs.map(addTwo) // x = [3, 4, 5, 6, etc]
There’s still one more change we can make that will (arguably) improve our
add
function. Right now, we’re manually creating and returning the closure,
and giving our function an unintuitive signature. But Swift actually supports
this kind of function out of the box. We can bring our function definition
back to something a little closer to what we started with, without losing the
currying functionality:
func add(a: Int)(b: Int) -> Int {
return a + b
}
This function is equivalent to our earlier implementation that had the closure, with the exception that now you need to name the second parameter:
let sum = add(2)(b: 3) // sum = 5
In fact, at the time of this writing, there is no way to define the function so that you can omit the external name.
This is fairly gross, but in this case it doesn’t impact us much at all. We
can still pass the partially applied function to map
as we did before.
func add(a: Int)(b: Int) -> Int {
return a + b
}
let addTwo = add(2)
let xs = 1...100
let x = xs.map(addTwo) // x = [3, 4, 5, 6, etc]
OK, cool, but what about functions I don’t own
If you don’t own the function you’re working with (yo what up UIKit
) or if
you don’t want the function to be curried by default (because let’s be honest,
that calling syntax is funky), you might think you’re out of luck. But I have
good news: you can implement a function that takes an existing function as a
parameter, and returns a curried wrapper around that function. And it uses
the same basic technique that we used to create our own curried function in
the first place.
Let’s pretend that instead of add
, the free function that we defined above,
we’re dealing with NSNumber.add
, a class method that I’m totally making up
for the sake of demonstration:
extension NSNumber {
static func add(_ a: NSNumber, _ b: NSNumber) -> NSNumber {
return NSNumber(value: a.integerValue + b.integerValue)
}
}
So now, if we decide that this function should be curried for some specific
use case (like being partially applied for map
), we want to be able to do
that.
First thing we need to do is define a function that takes a function of the
same type as NSNumber.add
as an argument. When you strip away the naming,
you end up with (NSNumber, NSNumber) -> NSNumber
. This will let us pass
NSNumber.add
into it directly. We’ll name this argument localAdd
internally to avoid confusion:
func curry(_ localAdd: (NSNumber, NSNumber) -> NSNumber) {
}
Then we can add the return value, which is a function that takes an NSNumber
and returns a new function. That function should take an NSNumber
and return
an NSNumber
. The type we end up with is (NSNumber) -> (NSNumber) ->
NSNumber
.
func curry(_ localAdd: (NSNumber, NSNumber) -> NSNumber) -> (NSNumber) -> (NSNumber) -> NSNumber {
}
Then we can use the trick from earlier and start returning closures:
func curry(_ localAdd: (NSNumber, NSNumber) -> NSNumber) -> (NSNumber) -> (NSNumber) -> NSNumber {
{ (a: NSNumber) in
{ (b: NSNumber) in
return localAdd(a, b) // returns an NSNumber
}
}
}
Update: Prior to SE-0103: Make non-escaping closures the default,
any Swift function was implicitly allowed to “escape” the context it was
defined in. In this example, the localAdd
closure escapes when it is
captured, or closed over, by the closure we’re returning from the curry
function. Here’s how we can update this function to compile under Swift 3+,
using the @escaping
attribute:
func curry(_ localAdd: @escaping (NSNumber, NSNumber) -> NSNumber) -> (NSNumber) -> (NSNumber) -> NSNumber {
{ (a: NSNumber) in
{ (b: NSNumber) in
return localAdd(a, b)
}
}
}
So a
and b
represent the two NSNumber
instances that will be passed to
localAdd
. So now, we could curry our NSNumber.add
function with our new
curry
function:
let curriedAdd = curry(NSNumber.add)
let addTwo = curriedAdd(2)
let xs = 1...100
let x = xs.map(addTwo) // [3, 4, 5, 6, etc]
This works really well, but we can actually use Generics to generalize our
curry
function to take arguments of any type. To start, we should figure out
how many types we need. In this case, we want to pass two variables and return
a third. These can all be of the same type, but they don’t have to be, so we
should probably use three generic types in our signature. Generic types are
usually shown as uppercase letters, so we’ll use A
, B
, and C
. Replacing
the explicit NSNumber
types with these generic types (and generalizing the
function name) leaves us with this:
func curry<A, B, C>(_ f: @escaping (A, B) -> C) -> (A) -> (B) -> C {
{ (a: A) in
{ (b: B) in
return f(a, b) // returns C
}
}
}
Now, to clean things up, we can take advantage of Swift’s type inference to remove the inner types:
func curry<A, B, C>(_ f: @escaping (A, B) -> C) -> (A) -> (B) -> C {
{ a in
{ b in
return f(a, b)
}
}
}
We can also take advantage of the implicit return values for single line closures and move the whole thing onto one line:
func curry<A, B, C>(_ f: @escaping (A, B) -> C) -> (A) -> (B) -> C {
return { a in { b in f(a, b) } }
}
Interestingly enough, since we’ve made our function completely generic, this
is actually the only way we could have possibly written the implementation in
order to get it to compile. So the entire concept is encoded directly into the
types. We have no idea what C
is, so the only way we know of to create an
instance of that type is to use f
. We also don’t know what A
or B
are,
so the only way we can get values to pass to f
are to use a
and b
.
That’s insanely powerful, since it means we can’t mess it up.
Also, since this function now works with any function that matches the type
(A, B) -> C
, we can use it on any function that matches this type signature.
Including the functions that power the standard operators. So, if we really
want to get wacky, we can re-write everything we’ve done so far like so:
let add = curry(+)
let xs = 1...100
let x = xs.map(add(2)) // [3, 4, 5, 6, etc]
This is super long. Wrap it up
If we take a look of that definition from the first paragraph, it hopefully doesn’t sound as much like gibberish anymore:
We have a function that takes multiple arguments. We then change that function so that it only takes one argument, and returns a function that takes the next argument, and so-on and so-forth until all arguments are satisfied. At that point (and only at that point), the calculations are performed, and a value is returned. We handled this for 2 arguments, but it’s the same process for as many arguments as you can throw at your functions.
What’s next
- Efficient JSON in Swift with Functional Concepts and Generics
- Real World JSON Parsing with Swift
- Parsing Embedded JSON and Arrays in Swift
- Using the Dropbox Objective-C API in Swift
- Functional Swift for Dealing with Optional Values
- Practical Use for Curried Functions in Swift
- Prelude on GitHub (Includes binary and
ternary implementations for
curry
)