Skip to content

Instantly share code, notes, and snippets.

@yuba
Last active August 29, 2015 13:57
Show Gist options
  • Save yuba/9657790 to your computer and use it in GitHub Desktop.
Save yuba/9657790 to your computer and use it in GitHub Desktop.
Either in TypeScript
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));
}
}
}
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