Last active
August 29, 2015 13:57
-
-
Save yuba/9657790 to your computer and use it in GitHub Desktop.
Either in TypeScript
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
module Functional { | |
export class Either<L, R> { | |
constructor(public apply: <TResult>(funcL: (p: L) => TResult, funcR: (p: R) => TResult) => TResult) { } | |
static left<L, R>(obj: L): Either<L, R> { | |
return new Either<L, R>(<TResult>(funcL: (p: L) => TResult, funcR: (p: R) => TResult) => funcL(obj)); | |
} | |
static right<L, R>(obj: R): Either<L, R> { | |
return new Either<L, R>(<TResult>(funcL: (p: L) => TResult, funcR: (p: R) => TResult) => funcR(obj)); | |
} | |
} | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
var either = Functional.Either.left<number[], string>([2, 3, 4]); | |
// gets sum for a array of number or length for a string | |
// 数列なら合計を、文字列なら長さを返す | |
var result = either.apply( | |
nums => nums.reduce((a,b) => a+b), | |
str => str.length | |
); | |
// prints enumeration for a array of number or a string | |
// 数列なら列挙表示、文字列ならそのまま表示 | |
either.apply( | |
nums => alert(nums.join(",")), | |
str => alert(str) | |
); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment