ref


ref(s, i, @optional default = false)
      

Return the element at index i from the sequence s. If the index is out of bounds, return default.

Ref and ref_set are generic functions that can be overridden by a user-defined object. Strings, lists, arrays and hash tables implement them by default. Any object that implement these functions automatically starts working with the [] syntax.

Examples:


let s = "heLLo, world"
ref(s, 10)
// \l
s[11]
// \d

ref(#{"one":1, "two":2}, "abc", 100)
// 100
ref(#{"one":1, "two":2}, "one")
// 1

// overriding ref and ref_set for a custom sequence:
function make_coll(xs)
  let (len = array_length(xs)
       coll_ref = ^(index) xs[index]
       coll_ref_set = ^(index, value) xs[index] = value)
    ^(msg)
    | 'first -> when (len > 0) array_at(xs, 0)
    | 'rest -> when (len > 1) make_coll(subarray(xs, 1, len))
    | 'count -> len
    | 'ref -> coll_ref
    | 'ref_set -> coll_ref_set

let b = make_coll(#[10, 20, 30])
b[0]
// 10
b[1] = 100
b[1]
// 100
ref(b, 2)
// 30
ref_set(b, 2, 200)
b[2]
// 200

// an object that responds to `ref` can be destructred as a list or a hash table:
let [x, y, z] = b
x + y + z
// 310

let #{0:i, 2:j, 1:k} = b;
[i, j, k]
// [10, 200, 100]
      

Also see:

ref_set
contains
first
rest
count
at


Core Module Index | Contents