Enum {matchr} | R Documentation |
Create Enumerated Type
Description
An object inspired by enums in Rust and types in other functional languages.
Usage
Enum(...)
Arguments
... |
Symbols specifying the named of the variant, or language call with the names and default values of objects
contained within the variant. Other values can be used as long as the variant is named. The first item in
|
Details
The Enum
function creates a list of objects of class "Enum" *or* functions that generate "Enum" objects
similar to those found in Rust of similar languages. Symbols or characters passed to Enum
become the new
variants. Language objects, i.e. a name followed by parentheses name(...)
, associate the name with the
variant and create a function based on the arguments passed in ...
. When function is called, the
passed arguments are converted into a named list of class "Enum" and associated variant. Like functions, default
values can be given to the variants.
Variants can be assigned specific values using '=
'. For example, Enum( Hello = "world" )
creates
an enum variant named "Hello" with the underlying value of "world"
. If the initial variant is assigned a
single numeric value, then subsequent variants are automatically assigned the next highest value if possible,
similar to using iota()
in Go. Variant names are not allowed to be numeric values or other non-symbolic
values.
Value
a list of variants or variant generators
Examples
### Create a Linked List
# Node is an enum with two varieties: a link to the next node, and none
# 'Node$Some' is a function that accepts two values and generates the enum
# variant, while 'Node$Empty' is a variant
Node <- Enum(
Some(Val, Next),
Empty
)
# Initialize an empty linked list, push values to the front
new_list <- Node$Empty
new_list <- Node$Some(1, new_list)
new_list <- Node$Some(2, new_list)
new_list
# return the head of the list ('car') and tail ('cdr')
car <- new_list$Val
cdr <- new_list$Next
### RGB Colors
# The Color enum is provided with a named type "Color". All
# variants will have both "Enum" and "Color" as a class.
# Each variant is associated with a specific value.
Color <- Enum(
"Color",
Black = c(0,0,0),
Red = c(255,0,0),
Green = c(0, 255, 0),
Blue = c(0, 0, 255),
White = c(255, 255, 255)
)
Color$Red
# This will generate an error since it is not a function
# Color$Black()
### Directions
# This enum creates a sequence of numbers associated with
# a particular direction. Enum automatically increments the
# values if the initial variant is assigned a single number
Direction <- Enum(
North = 1,
East,
South,
West
)
# This will result in '5' since North is '1' and West is '4'
Direction$North + Direction$West