Compound Types

The compound types, ie. types that reference other types, are mostly fairly straightforward.

In addition, the reader will construct a value from one of these simple types.

Operators

There’s no easy place to put value-index – other than close to its most common usage which is to pick apart compound types. The problem is that it is:

  • a reader standard operator

  • relies on the advanced work of Setters for its implementation

  • sneaks in some cheeky function application methods too

function o . i
function value-index o i

Here, in general, we want to get or set the ith element of o. This means we can write more readable code:

arr := #[ "one" "two" "three" ]
i := 0

; formal
array-ref arr i

; easier to read
arr.i

In most cases we can assign to the indexed element.

The possible types for o and effective accessors are:

type

ref

set

index from

pair

nth

1

string

string-ref

string-set!

0

array

array-ref

array-set!

0

hash

hash-ref

hash-set!

0

struct instance

struct-instance-ref

struct-instance-set!

C/pointer

[note 1]

[note 2]

note 1 This requires C Structure Identification support.

note 2 This requires a setter to be defined in

addition to C Structure Identification.

*

There is a cost to this as value-index doesn’t know the type of o so it has to do a some testing meaning it is a little slower than calling the type-specific accessor directly.

There is another use case where i is identified as a function (taking one argument) where the code rewritten as i o, ie. i is applied to o.

This form is very useful for functions such as fields which split a string using the delimiters in IFS.

Warning

value-index is a poor choice for library writers. In general, you cannot presume that a user has not defined a local variable that shadows your structure member name. As an obvious example, accessing a structure member called i as si.i is quite likely to expand to si.n for some n which is the current value of the user’s loop variable i.

define-struct will have created accessor functions such as st-i giving st-i si.

For libc structures always use a quoted symbol for the member name, libc/struct-tms-ref tms 'tms_utime.

Obviously, accessing specific values is fine, arr.4, although it will be quicker to access the underlying method directly, here, presumably, array-ref arr 4.

Last built at 2024-09-07T06:11:19Z+0000 from 463152b (dev)