asdlGen
Reference Manual
: Using the Code Produced
: De-constructing Data StructuresHere are some common idioms for De-constructing sum types based on the examples in The Rosetta Stone for Sum Types, for languages that do not support pattern matching. Languages such as ML can simply use pattern matching.
In C the common idiom should look something like this
M_sexpr_ty sexpr;
switch(sexpr->kind) {
case M_Int_kind: {
struct M_Int_s x = sexpr->v.M_Int;
/* access the fields through x */
} break;
case M_String_kind: {
struct M_String_s x = sexpr->v.M_String;
/* access fields through x */
} break;
....
case M_Cons_kind: {
struct M_Cons_s x = sexpr->v.M_Cons;
/* access the fields through x */
} break;
}
This approach introduces an extra structure copy which isn't necessary, but
has the advantage of enforcing a read only discipline on the
value. Alternatively nothing prevents you from accessing the fields directly
and mutating them as or making x
a pointer to a structure. A
carefully crafted set of macros could make this more readable.
In Java the idiom is much the same
import ast.*;
...
M.sexpr sexpr;
switch(M.sexpr.kind()) {
case M.sexpr.Int_kind: {
M.Int x = (M.Int) sexpr;
/* access the fields through x */
} break;
case M.sexpr.String_kind: {
M.String x = (M.String) sexpr;
/* access the fields through x */
} break;
...
case M.sexpr.Cons_kind: {
M.Cons x = (M.Cons) sexpr;
/* access the fields through x */
} break;
}
A series of instanceof
's in a chain if then else's would work also, but
this switch statement is likely to be faster. Unlike the C version this
idiom does not enforce a read only discipline since all object types are
reference types in Java.
For sum types which have been treated as enumerations
Sum Types as Enumerations the idioms are a bit different for C code. In
particular rather than switching on var->kind
in one would
switch on var
.
asdlGen
Reference Manual
: Using the Code Produced
: De-constructing Data Structures