2

TypeScriptでMaybeモナドで遊んでいます。概念についての私の理解はあまりよくないので、フィードバックや提案を歓迎します。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;
        }
    }
}
4

2 に答える 2

1

あなたのコードは良いです。いくつかのマイナーな提案のみ。

JSドキュメント

好む

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

単一行の JSDoc コメントおよび

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

複数行の場合

その他の実装

コードプレックスの問題もあります: https ://typescript.codeplex.com/workitem/2585と実装: https ://gist.github.com/khronnuz/1ccec8bea924fe98220e <これは反復に焦点を当てていますが、あなたのものは継続に焦点を当てています

于 2014-07-14T23:39:55.787 に答える