choice.h¶
Choice types: (tag, ...)
.
A choice type, also known as tagged union, is represented as (tag, ...)
, where tag
is the type of a value and ...
is the value. Perhaps the most common example of a choice type is a binary tree:
// Sums all nodes of a binary tree, recursively.
#include <metalang99.h>
#define leaf(x) ML99_choice(v(leaf), x)
#define node(lhs, data, rhs) ML99_choice(v(node), lhs, data, rhs)
#define sumTree(tree) ML99_match(tree, v(sumTree_))
#define sumTree_leaf_IMPL(x) v(x)
#define sumTree_node_IMPL(lhs, data, rhs) ML99_add3(sumTree(v(lhs)), v(data), sumTree(v(rhs)))
/*
* 4
* / \
* / \
* / \
* 2 6
* / \ / \
* 1 3 5 7
*/
#define TREE node(node(leaf(v(1)), v(2), leaf(v(3))), v(4), node(leaf(v(5)), v(6), leaf(v(7))))
ML99_ASSERT_EQ(sumTree(TREE), v(28));
int main(void) {}
Defines
-
ML99_choice(tag, ...)¶
Constructs an instance of a choice type.
Examples
Note
Specify
~
if you do not want to supply data; then, to match it, write a_
parameter to ignore.
-
ML99_choiceTag(choice)¶
Evaluates to the tag of
choice
.This macro is essentially the same as
ML99_tupleGet(0)
.Examples
#include <metalang99/choice.h> // foo ML99_choiceTag(ML99_choice(v(foo), v(1, 2, 3)))
-
ML99_choiceData(choice)¶
Evaluates to the data of
choice
.This macro is essentially the same as ML99_tupleTail.
Examples
#include <metalang99/choice.h> // 1, 2, 3 ML99_choiceData(ML99_choice(v(foo), v(1, 2, 3)))
-
ML99_match(choice, matcher)¶
Matches the instance
choice
of a choice type.This macro results in
ML99_call(ML99_cat(matcher, ML99_choiceTag(choice)), <choice data>)
.Examples
-
ML99_matchWithArgs(choice, matcher, ...)¶
The same as ML99_match but supplies additional arguments to all branches.
This macro results in
ML99_call(ML99_cat(matcher, ML99_choiceTag(choice)), <choice data>, args...)
.Examples
#include <metalang99/choice.h> #define MATCH_A_IMPL(x, y, z) v(x ~ y ~ z) // 123 ~ 456 ~ 789 ML99_matchWithArgs(ML99_choice(v(A), v(123)), v(MATCH_), v(456, 789))
-
ML99_CHOICE(tag, ...)¶
-
ML99_CHOICE_TAG(choice)¶
-
ML99_CHOICE_DATA(choice)¶