Enums and flags

Enums

An enum value has a fixed set of possibilities.

main void() log opposite left direction enum left right opposite direction(a direction) if a == left right elif a == right left else throw unreachable

Short enums can be squeezed onto a single line.

direction enum(left, right)

Declaring an enum implicitly declares many functions:

FunctionDescription
== bool(a direction, b direction)Exact equality.
<=> comparison(a direction, b direction)Enum members declared earlier are less.
hash void(a direction, state hash-state)Hashes the numeric value.
to json(a direction)json value that is the name of the enum member.
to symbol(a direction)The name of the enum member.
to direction?(a symbol)Gets an enum member by name.
to nat(a direction)Numeric value of the enum member.
to direction?(a nat)Gets an enum member by value.
members direction[]()Array of every enum member.

Conversion from symbol or nat returns an option, because not all symbols and nat are valid directions.

main void() log "equal", left == left log "compare", left <=> right log "to symbol", to::symbol left log "from symbol", to::direction? "left" log "from wrong symbol", to::direction? "both ways" log "to nat", to::nat left log "from nat", to::direction? 1 log "from wrong nat", to::direction? 2 log "all members", members::direction[] direction enum(left, right)

"match" on enums

A more convenient way to use an enum is with a match expression.

main void() log opposite left direction enum(left, right) opposite direction(a direction) match a as left right as right left

Enum numbers

You can customize the number values used for the enum.

main void() log to::nat left direction enum left = 5 right = 10

Flags

A flags value can contain any combination of the declared flags.

main void() apple = carry | eat | toss soup = carry | eat rock = carry | toss log "apple picnic?", can-picnic apple log "soup picnic?", can-picnic soup log "rock picnic?", can-picnic rock log "flags a rock lacks:", ~rock log "rock and soup have in common:", rock & soup log "flags in either rock or soup:", rock | soup actions flags carry eat toss can-picnic bool(a actions) a[carry | eat]

Declaring a flags type implicitly defines all of the same functions as for an enum, plus several additional functions. In the above example those are:

FunctionUse
new actions()Value with no flags set.
carry actions()Value with just the carry flag set.
eat actions()Value with just the eat flag set.
toss actions()Value with just the toss flag set.
~ actions(a actions)Value with the opposite flags set.
| actions(a actions, b actions)Union; contains any flags that appear in either argument.
& actions(a actions, b actions)Intersection; contains only the flags that both arguments agree on.
subscript bool(a actions, b actions)True if a contains every flag in b. Written as a[b].

flags types also support all the usual auto functions.