recur
Module to conveniently run closures recursively
Use-case for this are:
- Maintain a state while sharing resources easily
- Run operation forever
- Limit the number of iterations in a recurring closure
recur.with(with: #([], 0), run: fn(state) {
let #(is, i) = state
case i < 5 {
True -> {
let i = i + 1
recur.Continue(#(list.prepend(is, i), i))
}
_ -> recur.Break(is)
}
})
Types
Values
pub fn atmost_with(
init state: state,
limit max: Int,
run function: fn(state) -> Next(state, result),
) -> Result(result, state)
Start a recurrence with guard on max number of iterations, returns like normal with, otherwise Error(state) after crossing the iteration limit.
Examples
assert Error(#([3, 4, 5], 2))
== recur.atmost_with(init: #([], 5), limit: 3, run: fn(state) {
let #(is, i) = state
use <- bool.guard(i == 0, recur.Break(is))
recur.Continue(#([i, ..is], i - 1))
})
pub fn try_inf(
init state: state,
run f: fn(state) -> Result(state, err),
) -> Result(Nil, err)
pub fn try_with(
init state: state,
run function: fn(state) -> Result(Next(state, result), err),
) -> Result(result, err)
Start a fallible recurrence and return the result when the function successfully returns Break or an Error if it fails.
Examples
assert Error(Nil)
== recur.try_with(init: #([], 5), run: fn(state) {
let #(is, i) = state
use <- bool.guard(i == 0, Error(Nil))
recur.Continue(#([i, ..is], i - 1)) |> Ok
})
pub fn with(
init state: state,
run function: fn(state) -> Next(state, result),
) -> result
Start a recurrence and return the result when the function returns Break.
Examples
assert [1, 2, 3, 4, 5]
== recur.with(init: #([], 5), run: fn(state) {
let #(is, i) = state
use <- bool.guard(i == 0, recur.Break(is))
recur.Continue(#([i, ..is], i - 1))
})