compose {kriens}R Documentation

Continuation Passing Style Function Composition

Description

It allows to compose two functions of the form f(x, ret) and g(x, ret) returning a function h(x,ret) which is the composition f \circ g. It implements the composition operator of the Continuation category.

The the composition has the following properties:

  1. Associativity: h \circ (f \circ g) = ( h \circ g) \circ f

  2. Unity: f \circ identity2 = f = identity2 \circ f

In order for these relations to hold, the function f and g must not deal with global mutable states.

Usage

compose(f, g)

Arguments

f

The first function that must be composed

g

The first function that must be composed

Value

Rerturns the composite function of f and g

Note

The composition is performed from left to right i.e. such that the first function executed is f.

Author(s)

Matteo Provenzano
http://www.alephdue.com

See Also

forget

Examples

# Example 1

# define an arrow in the Continuation category.
# this function applies the continuation to the
# increment of its argument and then decrements it.
one <- function(x, ret) {
    return(ret(x+1) - 1)
}

# define another arrow in the Continuation category.
# this function doubles its argument.
two <- function(x, ret) {
    return(ret(2*x))
}

# create the composition
# this is exactly the same as one %.% two
composite <- compose(one, two)

# build the function (forget the continuation)
execute1 <- forget(composite)
execute1(1)
# returns 3

# Example 2
# compose the function further to loop over an array of elements
# lapply and sapply are already arrow in the Continuation category
loop <- compose(lapply, composite)

# build the function
execute2 <- forget(loop)
execute2(1:10)

[Package kriens version 0.1 Index]