lambda
lambda copied to clipboard
Maybe's
#83 removed null
. There are still important use cases for nullary values where undefined
is unsuitable because it wouldn't type.
For example, binary trees:
# assumption: io.read returns undefined at EOF
let Node = fix fn Node, this, label ->
if label = undefined
then undefined
else let this.label = label,
this.left = new Node io.read,
this.right = new Node io.read,
this.height = fn this ->
if this = undefined
then 0
# type error here: this.left and this.right do not necessarily have a "height" field
else 1 + {this.left.height, this.right.height}.max
in this
in
let io.read_node = fn io -> (new Node io.read) in
io.read_node.height
The best solution is to replace null
with Haskell-style maybe
's. The above would become:
# assumption: io.read returns a maybe
let Null.height = fn this -> 0 in
let Node = fix fn Node, this, label ->
let this.label = label,
this.left = io.read (new Node) Null,
this.right = io.read (new Node) Null,
this.height = fn this ->
1 + {this.left.height, this.right.height}.max
in this
in
let io.read_node = fn io -> (io.read (new Node) Null) in
io.read_node.height
Implement the following terms:
- just ≡ λ v, f, z . f v
- nothing ≡ λ f, z . z
- fmap ≡ λ f, m . m (λ v . just (f v)) nothing
- bind ≡ λ m, f . m f nothing
Incidentally, nothing
is alpha-equivalent to false
.
#89 might actually obsolete all the use cases of "nullable" values, but maybe's would still be useful to handle failures.