Skip to content

Pipelines

To prevent deeply nested function applications, Kura provides the forward pipeline operator (|>).

The pipeline operator feeds the evaluated result of its left-hand expression as the first parameter of the function invocation on its right-hand side.

fn piped(p: Position): Message =>
p |> Click()
// The expression above compiles exactly down to:
// Click(p)

Pipelines are particularly useful for sequencing long series of data modifications or layout scaling transformations without managing temporary variable states.

let processed = raw_coords
|> scale_dimensions()
|> center_bounds()
|> Click()

Kura provides both forward and backward (reverse) pipeline composition.

Unlike the pipeline operator |>, the operators >> and << are purely compositional - they construct a new function and do not trigger immediate evaluation.

Using the forward-pipeline operator >> you can link functions together from left-to-right:

fn add(a: Int, b: Int): Int => a + b
fn sub(a: Int, b: Int): Int => a - b
fn mul(a: Int, b: Int): Int => a * b
fn div(a: Int, b: Int): Int => a / b
let pipe = add(10) >> mul(2)
let x = 10 |> pipe() // => 40
// Compiles down to:
// mul(add(10, 10), 2) -> mul(20, 2) -> 40

Using the reverse-pipeline operator <<, you can link functions together from right-to-left:

fn add(a: Int, b: Int): Int => a + b
fn sub(a: Int, b: Int): Int => a - b
fn mul(a: Int, b: Int): Int => a * b
fn div(a: Int, b: Int): Int => a / b
let pipe = add(10) << mul(2)
let x = 10 |> pipe() // => 30
// Compiles down to:
// add(10, mul(2, 10)) -> add(10, 20) -> 30

When a function requires the piped value at a position other than the first argument, use the placeholder (_) to explicitly mark the target slot.

fn add(a: Int, b: Int): Int => a + b
fn sub(a: Int, b: Int): Int => a - b
fn mul(a: Int, b: Int): Int => a * b
fn div(a: Int, b: Int): Int => a / b
let y = 10 |> mul(_, 20) // => 200
// Can also be expressed as:
let y = 10 |> mul(20) // => 200
let x = 10 |> div(20, _) // => 2
fn add(a: Int, b: Int): Int => a + b
fn sub(a: Int, b: Int): Int => a - b
fn mul(a: Int, b: Int): Int => a * b
fn div(a: Int, b: Int): Int => a / b
let pipe = add(1) >> div(100, _)
let x = pipe(1) // => 50
// Resolves the composition down to:
// div(100, add(1, 1)) -> div(100, 2) -> 50

The placeholder doesn’t have to be a whole argument. Everywhere a _ appears in the stage, the piped value goes there, and it is computed once:

let x = 10 |> _ + 1 // 11
let y = 4 |> mul(_, _) // 16

Outside a pipeline, a _ is only allowed as a whole argument of a call (div(100, _)), where it leaves that argument open.

f <| x applies the function on its left to the value on its right. It is read from the right, so f <| g <| x is f(g(x)). The two directions can’t be mixed in one chain without parentheses: (x |> f()) |> g().