Ink by Example — Control Flow

Ink by Example: Control Flow

Instead of if/else branching, match expressions are used for control flow.

std := load('../vendor/std')
filter := std.filter
log := std.log


Like the switch expression from other programming languages, the case clauses are checked from top to bottom. The checking stops when there's a match.

error := true
error :: {
    false -> log('No problem!')
    true -> log('There is a problem..')
}

The default, or else, branch is signified with the underscore character. This will match anything.

device := 'windows'
device :: {
    'linux' -> log('Linux!')
    'macOS' -> log('Mac!')
    _ -> log('Neither Linux or Mac.')
}

A match target can be an expression.

greeting := 'Hello!'
greeting :: {
    'Hello' -> log('They greeted us.')
    'Hello' + '!' -> log('They greeted us loudly.')
}

Composite values are deep compared so the underscore can be used to catch complex objects that, while different, have a similar characteristic.

first := {
    code: 2,
    user: 'alice@google'
}
second := {
    code: 2,
    user: 'claire@amazon'
}

checkEvent := event => event :: {
    {code: 2, user: _} -> log('All good!')
    _ -> log('Bad event..')
}
checkEvent(first)
checkEvent(second)

std.filter can be passed a match expression. Here we use it to filter out odd numbers.

numbers := [1, 2, 3, 4, 5, 6]
onlyEven := num => num % 2 :: {
    0 -> true
    _ -> false
}
even := filter(numbers, onlyEven)
log(even)

$ ink control-flow.ink
There is a problem..
Neither Linux or Mac.
They greeted us loudly.
All good!
All good!
{2: 6, 0: 2, 1: 4}

Next example: Lists.