FOSS Unleashed

XS List Operations (shift, unshift, push, pop)

All variables in XS are lists, this means that working with any kind of data that can be represented as an array of simple types (IE: ints or strings), can be handled by XS in a very simple manner.

shift

One of the list operations someone might need is to shift an item out of the front of the list, we can use the “multiple assignment” feature of XS to perform this operation:

; list = 1 2 3 4 5 6 7 8
; (a list) = $list
; var a list
a = 1
list = 2 3 4 5 6 7 8

Note: the var command simply prints the name and value of variables.

unshift

Prepending items to an array is commonly known as unshifting, XS will flatten all lists, making this operation trivial:

; list = 0 1 $list
; var list
list = 0 1 2 3 4 5 6 7 8

push

Appending items to an array is exactly as simple as unshift is, and this is often called pushing onto the array.

; list = $list 9 10
; var list
list = 0 1 2 3 4 5 6 7 8 9 10

pop

Removing the last item of an array is no longer trivial, so we have a helper that takes the last item and puts it at the front, letting us shift the final value out.

; (a list) = <={ %shift $list }
; var a list
a = 10
list = 0 1 2 3 4 5 6 7 8 9

The code for the %shift fragment can be seen here:

fn %shift {|l|
    let (n = $#l; m) {
        if {~ $n 0 1} {
            # nothing to do, do nothing
            result $l
        } else if {~ $n 2} {
            result $l(2 1)
        } else {
            m = `($n - 1)
            result $l($n 1 ... $m)
        }
    }
}