我正在使用 TypeScript 中的 Maybe monad。我对这些概念的理解不是很好,所以我欢迎任何反馈或建议。有很多 JS 示例,但我正在寻找更强大的类型。
用法类似于:
var maybe = new Example.Maybe({ name: "Peter", age: 21 })
.ifF(p => p.age === 100) // is the person 100?
.returnF(p => p.name, "Unknown") // extract Maybe string of name
.getValue(); // unwrap the string from the Maybe
因为 if/with/return 是保留字,所以我刚刚在末尾添加了 F ..
到目前为止,我有:
module Example
{
export class Maybe<T>
{
private val: T;
private hasv: boolean;
private static none = new Maybe(null);
constructor(value: T)
{
this.val = value;
this.hasv = (value != null);
}
/** True if Maybe contains a non-empty value
*/
hasValue(): boolean
{
return this.hasv;
}
/** Returns non-empty value, or null if empty
*/
getValue(): T
{
if (this.hasv) return this.val;
return null;
}
/** Turns this maybe into Maybe R or Maybe NONE if there is no value
*/
withF<R>(func: (v: T) => R) : Maybe<R>
{
if (!this.hasv) return Maybe.none;
return new Maybe<R>(func(this.val));
}
/** Turns this maybe into Maybe R or Maybe DefaultVal if there is no value
*/
returnF<R>(func: (v: T) => R, defaultval: R): Maybe<R>
{
if (!this.hasv) return new Maybe(defaultval);
return new Maybe<R>(func(this.val));
}
/** If func is true, return this else return Maybe NONE
*/
ifF(func: (v: T) => boolean): Maybe<T>
{
if (!this.hasv) return Maybe.none;
if (func(this.val))
return this;
else
return Maybe.none;
}
}
}