Apple Swift: Emulate Partial Fully Applied Functions

This article is only a short one, that tells an obvious fact, but I love it; hence, I will let you participate. Currently, I am doing a project with the new language Swift from Apple. Swift is a object-functional language like e.g. Scala.

Both languages have the nice functionality partial application of functions. This means you can set some of the parameters which returns a function that has the remaining parameters, only. So, it is not yet executed, but the already passed parameters are stored into the partial applied function and used if it is called with the rest of the parameters. Just for the seek of completeness, currying is then, when a function with multiple parameters is decomposed into a chain of functions that each has exactly one parameter (this is not the same).

But hey, this should be a short one. Here comes the punch line: You can partially apply functions, so that they have only one parameter, but what if I would like to preset all the parameters? It is very simple: Use a closure to create a new anonymous function, that simply executes the function of interest with all its parameters.

So, a closure is an anonymous function (i.e. a lambda function), which is able to capture variables that are in its scope. For Java programmers (i.e. before Java 8): It is very similar to anonymous classes (of course only, if you would refer functions very similar to classes, which is a valid position for sadomasochistic inclined individuals).

I did not try to implement this in Java 8 and I don’t know how well type inference is supported there, so that this does not get messy, but in Swift it looks like this:

func foo(bar: String) -> String {
  return "foo \(bar)"
}
let fooBar = {foo("bar")}
// results in a closure: () -> String

println(fooBar())
// prints: "foo bar"

In the short expression {foo("bar")} hides the declaration of a closure that automatically adapts the return value of the only statement foo("bar"). LIKE.

Exciting.

Leave a Reply

Your email address will not be published. Required fields are marked *