Skip to content

Instantly share code, notes, and snippets.

@hasithaa
Last active April 24, 2023 10:57
Show Gist options
  • Save hasithaa/5a50ad63dfc2624647a8ceaaaa5dfdcd to your computer and use it in GitHub Desktop.
Save hasithaa/5a50ad63dfc2624647a8ceaaaa5dfdcd to your computer and use it in GitHub Desktop.
Record Visitor Pattern
import ballerina/io;
// Type Nodes
type Node record {
string kind;
string value;
};
type NodeA record {
*Node;
"NodeA" kind = "NodeA";
string value;
};
type NodeB record {
*Node;
"NodeB" kind = "NodeB";
string value;
int count;
};
// Actual Node vistor Logic
function visitNodeA(NodeA node) {
io:println("Do something with NodeA", node);
}
function visitNodeB(NodeB node) {
io:println("Do something with NodeB", node);
}
// Node visitor dispatcher
function visit(Node node) returns error? {
match node.kind {
"NodeA" => {
visitNodeA(check node.ensureType());
}
"NodeB" => {
visitNodeB(check node.ensureType());
}
}
}
public function main() returns error? {
Node[] nodes = [
{kind: "NodeA", value: "A"},
{kind: "NodeB", value: "B", "count": 1},
{kind: "NodeA", value: "C"}
];
foreach var node in nodes {
check visit(node);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment