Last active
October 22, 2021 15:14
-
-
Save hallettj/281e4080c7f4eaf98317 to your computer and use it in GitHub Desktop.
Algebraic data type in Javascript with Flow
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/* @flow */ | |
type Tree<T> = | |
| { type: "Node", value: T, left: Tree<T>, right: Tree<T> } | |
| { type: "EmptyTree" } | |
function find<T>(p: (v: T) => boolean, t: Tree<T>): T | void { | |
var l, v | |
if (t.type === "Node") { | |
l = find(p, t.left), v = t.value | |
if (typeof l !== 'undefined') { | |
return l | |
} | |
else if (p(v)) { | |
return v | |
} | |
else { | |
return find(p, t.right) | |
} | |
} | |
else if (t.type === "EmptyTree") { | |
// We would get an error here if we tried to reference `t.value`, `t.left`, | |
// or `t.right`, because the "EmptyTree" shape does not have those things. | |
return undefined | |
} | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
type Tree<T> = Node<T> | EmptyTree | |
class Node<T> { | |
value: T; | |
left: Tree<T>; | |
right: Tree<T>; | |
constructor(value, left, right) { | |
this.value = value | |
this.left = left | |
this.right = right | |
}; | |
} | |
class EmptyTree {} | |
function find<T>(p: (v: T) => boolean, t: Tree<T>): T | void { | |
var l, v; | |
if (t instanceof Node) { | |
l = find(p, t.left), v = t.value | |
if (typeof l !== 'undefined') { | |
return l | |
} | |
else if (p(v)) { | |
return v | |
} | |
else { | |
return find(p, t.right) | |
} | |
} | |
else if (t instanceof EmptyTree) { | |
return undefined; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment