Maybe
在haskell里,我们有:
Maybe a = Just a | Nothing
Typescript中实现
class Optional<T> {
private _isValid: boolean = null;
private _value: T = null;
constructor (v: T = null) {
if (v) {
this._isValid = true;
this._value = v;
} else {
this._isValid = false;
}
}
getValue () {
return this._value;
}
isValid () {
return this._isValid;
}
}
// 使用
// 保证返回的是一个Optional对象,而不是Null
// 可以走通整个后续流程
function getPlayerById(id: number): Optional<Player> {
let player = world.players[i];
return new Optional(player);
}
function fmap(func, player: Optional<Player>) : Optional<string>;
function fmap_fmap (func, arr: Array<Optional<Player>>): Array<Optional<string>>;
// fmap ::Functor f => (a -> b) -> f a -> f b
// fmap_fmap = fmap . fmap :: (Functor f, Functor f1) => (a -> b) -> f1 (f a) -> f1 (f b)