ref

A ref cell library for gleam. The implementation uses actors on the erlang target for keeping track of the values of references, so a new process is spawned for each mutable reference you create. These mutable references should only be used if mutability is absolutely required. Immutability should always be preferred, and this implementation loses the performance benefits that mutability generally provides.

Types

The reference cell type for holding mutable data

pub opaque type RefCell(a)

Functions

pub fn cell(contents: a) -> RefCell(a)

Public constructor for creating a new RefCell. The initial value is passed, and a RefCell containing that value is returned.

Examples

let immutable_value: List(Int) = [1, 2, 3, 4]
let mutable_copy: RefCell(List(Int)) = ref.cell(immutable_value)
pub fn get(cell: RefCell(a)) -> a

Used for extracting the held data in a RefCell. Once the value has been extracted with this function, any mutations on the Cell will not affect the data already extracted. On erlang, this may panic if the actor is dead. If you want to return a result instead, use try_get. On javascript, get should always be used.

Examples

let state = ref.cell(20)
ref.get(state) |> io.debug
// > 20
ref.set(state, fn(a) { a + 5 })
ref.get(state) |> io.debug
// > 25
pub fn kill(cell: RefCell(a)) -> Nil

On erlang, this will shut down the underlying actor holding the state of a RefCell. On javascript, this will do nothing,

Examples

let state = ref.cell([1, 2, 3])
ref.kill(state)
ref.try_get(state) |> io.debug
// > Error(_)
pub fn map(subj: RefCell(a), f: fn(a) -> b) -> RefCell(b)

Map the result of a function taking a Cell’s contents into a new RefCell. No mutation takes place

pub fn set(cell: RefCell(a), operation: fn(a) -> a) -> a

Pass a function that takes and returns the inner type of the RefCell, and set the contents of the cell to its return value

Examples

let state = ref.cell([1, 2, 3])
ref.set(state, fn(a) { list.map(a, fn(b) { b + 1 }) })
// or
use ls <- ref.set(state)
list.map(ls, fn(a) { a + 1 })
// state -> RefCell([2, 3, 4])
pub fn try_get(cell: RefCell(a)) -> Result(a, CallError(a))

Similar to ref.get, but will return a result instead of panicking if the actor is dead.

Examples

let state = ref.cell(20)
ref.try_get(state) |> io.debug
// > Ok(20)
ref.set(state, fn(a) { a + 5 })
ref.try_get(state) |> io.debug
// > Ok(25)
ref.kill(state)
ref.try_get(state) |> io.debug
// > Error(_)
Search Document