1.9. Closures

Functions are first-class values in Orc. Defining a function creates a special value called a closure; the defined name of the function is a variable and the value bound to it is the closure. A closure can be published, passed as an argument to a call, or put into a data structure, just like any other value.

Since all declarations — including function declarations — are lexically scoped, these closures are lexical closures. When a closure is created, if the body of the function contains any variables other than the formal parameters, closure creation blocks until those variables are bound, and then the values bound to those variables are stored as part of the closure. Then, when the closure is called, the evaluation of the function body uses those stored bindings.

1.9.1. Type

The type of a closure is a function type lambda [X0 ,, Xm](T0 ,, Tn) :: R, where Ti are the argument types of the closure, R is its return type, and Xj are the type parameters if the function is polymorphic. This type is derived from the original definition of the function.

1.9.2. Examples

Staged Addition
{- Create a closure using inc, and then apply it -}

def inc(n) = 
  def addnto(x) = x + n
  addnto
  
val f = inc(3)
f(4)

{-
OUTPUT:
7
-}
One Two Sum
{- The function triple() is used as a closure -}

def onetwosum(f) = f(1) + f(2)
def triple(x) = x * 3
onetwosum(triple)

{-
OUTPUT:
9
-}

1.9.3. Related Links

Related Tutorial Sections