Skip to content

Instantly share code, notes, and snippets.

@coffeemug
Last active July 2, 2020 23:27
Show Gist options
  • Save coffeemug/04c6795e6441196f5ee820843807879d to your computer and use it in GitHub Desktop.
Save coffeemug/04c6795e6441196f5ee820843807879d to your computer and use it in GitHub Desktop.
fn print<T>(x: T) {
// backticks inject Golang code directly. This isn't
// type-checked or processed by Axler. Any Axler variable
// must be marshalled via `<%=` and `%>`
`fmt.Printf("%v\n", <%= x %> )`
}
enum maybe<T> = none | some(T);
// `T?` is syntax sugar for `maybe<T>`. Just a convenient way
// to indicate that the variable is nullable.
fn value_or<T>(opt: T?, default: T) -> T {
switch (opt) {
none => default,
some(x) => x,
}
}
struct node_t {
left: node_t?,
right: node_t?,
key: i32,
}
fn insert(node: node_t?, key: i32) -> node_t {
let node = value_or(node, node_t { left: none, right: none, key, });
if (key < node.key) {
node.left = some(insert(node.left, key));
}
if (key > node.key) {
node.right = some(insert(node.right, key));
}
node;
}
fn dfs(node: node_t?) {
switch (node) {
none => {},
some(node) => {
dfs(node.left);
print(node.key);
dfs(node.right);
},
}
}
// Currently if a function expects `maybe<T>` you can't just
// pass `T`. It has to be wrapped in the `some` constructor.
// This is very annoying, as is visible here. I'm going to
// add a way to define implicit coercion so this annoyance
// goes away.
let root = insert(none, 10);
root = insert(some(root), 5);
root = insert(some(root), 7);
root = insert(some(root), 15);
root = insert(some(root), 13);
dfs(some(root));
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment