也许是TypeScript中的monad

时间:2014-07-14 16:46:23

标签: typescript monads maybe

我正在使用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

因为如果/ 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;
        }
    }
}

2 个答案:

答案 0 :(得分:1)

你的代码很好。只有一些小建议。

JS DOC

首选

/** True if Maybe contains a non-empty value */

用于单行JSDoc注释和

  /** 
    * True if Maybe contains a non-empty value
    */

用于多行的

其他实现

还存在一个codeplex问题:https://typescript.codeplex.com/workitem/2585,其实现:https://gist.github.com/khronnuz/1ccec8bea924fe98220e&lt;这个专注于迭代,因为你的重点是继续

答案 1 :(得分:1)

在构建这些东西时,我建议参考幻想世界规范。 WithF通常称为过滤器,returnF / withF可以用map / chain代替。 orJust是另一种方法,如果您的流什么都不返回,则允许您提供默认值。

var maybe = new Example.Maybe({ name: "Peter", age: 21 })
    .filter(p => p.age === 100)
    .map(p => p.name)    
    .orJust('unknown');  

https://github.com/fantasyland/fantasy-land

根据规范实现功能时,无需考虑太多事情。您也可以很容易地切换到其他数据类型(例如数组/列表),因为这些方法也将存在于新类型上。

相关问题