2019-02-24 08:33:20 -06:00
|
|
|
// maybe is our monadic optional. It wraps a value that may or may not be the empty
|
|
|
|
// type NULL. It exports three operations.
|
|
|
|
//
|
|
|
|
// * do - runs a user provided function of one argument on the value.
|
|
|
|
// Returns a maybe wrapped result.
|
2019-02-28 20:59:17 -06:00
|
|
|
//
|
|
|
|
// * or - runs a user provided function of no arguments if the value is NULL.
|
|
|
|
// Returns a maybe wrapped result.
|
2019-02-24 08:33:20 -06:00
|
|
|
//
|
|
|
|
// * is_null - a function with no arguments that returns true if the value is
|
|
|
|
// NULL and false if it is not.
|
|
|
|
//
|
|
|
|
// * unwrap - returns the wrapped value from the maybe.
|
|
|
|
//
|
|
|
|
// * expect - Throws a compile error if the value is NULL.
|
2019-01-16 18:47:16 -06:00
|
|
|
let maybe = module{
|
|
|
|
val = NULL,
|
2019-02-28 20:59:17 -06:00
|
|
|
} => ({do=do, is_null=is_null, or=or, unwrap=unwrap, expect=expect}) {
|
2019-02-24 08:33:20 -06:00
|
|
|
let maybe = import "std/functional.ucg".maybe;
|
|
|
|
|
|
|
|
let do = func (op) => select (mod.val != NULL), maybe{val=NULL}, {
|
|
|
|
true = maybe{val=op(mod.val)},
|
2019-01-16 18:47:16 -06:00
|
|
|
};
|
|
|
|
|
2019-02-28 20:59:17 -06:00
|
|
|
let or = func (op) => select (mod.val == NULL), maybe{val=mod.val}, {
|
|
|
|
true = maybe{val=op()},
|
|
|
|
};
|
|
|
|
|
2019-02-24 08:33:20 -06:00
|
|
|
let is_null = func() => mod.val == NULL;
|
|
|
|
|
|
|
|
let unwrap = func() => mod.val;
|
|
|
|
|
|
|
|
let expect = func(msg) => select mod.val != NULL, fail msg, {
|
|
|
|
true = mod.val,
|
2019-01-16 18:47:16 -06:00
|
|
|
};
|
|
|
|
};
|
|
|
|
|
2019-02-24 08:33:20 -06:00
|
|
|
// identity is the identity function.
|
2019-01-24 20:04:40 -06:00
|
|
|
let identity = func (arg) => arg;
|