47 lines
1.0 KiB
Plaintext
47 lines
1.0 KiB
Plaintext
// Demonstrating algebraic data types and pattern matching
|
|
|
|
// Define a binary tree
|
|
type Tree =
|
|
| Leaf(Int)
|
|
| Node(Tree, Tree)
|
|
|
|
// Sum all values in a tree
|
|
fn sumTree(tree: Tree): Int =
|
|
match tree {
|
|
Leaf(n) => n,
|
|
Node(left, right) => sumTree(left) + sumTree(right)
|
|
}
|
|
|
|
// Find the depth of a tree
|
|
fn depth(tree: Tree): Int =
|
|
match tree {
|
|
Leaf(_) => 1,
|
|
Node(left, right) => {
|
|
let leftDepth = depth(left)
|
|
let rightDepth = depth(right)
|
|
1 + (if leftDepth > rightDepth then leftDepth else rightDepth)
|
|
}
|
|
}
|
|
|
|
// Example tree:
|
|
// Node
|
|
// / \
|
|
// Node Leaf(5)
|
|
// / \
|
|
// Leaf(1) Leaf(2)
|
|
|
|
let myTree = Node(Node(Leaf(1), Leaf(2)), Leaf(5))
|
|
let total = sumTree(myTree)
|
|
let treeDepth = depth(myTree)
|
|
|
|
// Option type example
|
|
fn safeDivide(a: Int, b: Int): Option<Int> =
|
|
if b == 0 then None
|
|
else Some(a / b)
|
|
|
|
fn showResult(result: Option<Int>): String =
|
|
match result {
|
|
None => "Division by zero!",
|
|
Some(n) => "Result: " + n
|
|
}
|