recur

Module to conveniently run closures recursively

Use-case for this are:

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

Message to the executer if the recurrence should continue or break with a result.

pub type Next(state, result) {
  Continue(state)
  Break(result)
}

Constructors

  • Continue(state)

    Continue the recurrence with new state.

  • Break(result)

    Break the recurrence with a result.

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 inf(init state: state, run f: fn(state) -> state) -> Nil
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)) })

✨ Search Document