Created
January 18, 2015 11:29
-
-
Save minoki/2732f2d723ef0816fc8e to your computer and use it in GitHub Desktop.
An example of the coproduct type 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
interface Sum<A,B> | |
{ | |
elim<C>(left: (value: A) => C, right: (value: B) => C): C; | |
} | |
function Left<A>(value: A): {elim<C>(left:(value:A)=>C,right:(value:any)=>C):C;} | |
{ | |
return { | |
elim: <C>(left: (value: A) => C, right: (value: any) => C) => left(value) | |
}; | |
} | |
function Right<B>(value: B): {elim<C>(left:(value:any)=>C,right:(value:B)=>C):C;} | |
{ | |
return { | |
elim: <C>(left: (value: any) => C, right: (value: B) => C) => right(value) | |
}; | |
} | |
// An example | |
function modulo2(x: number): Sum<number, number> | |
{ | |
if (x % 2 === 0) { | |
return Left(x/2); | |
} else { | |
return Right((x-1)/2); | |
} | |
} | |
var a = modulo2(42); | |
console.log(a.elim( | |
x => "a is 2*" + x.toString(), | |
y => "a is 2*" + y.toString() + "+1" | |
)); | |
// Another example | |
String.prototype.repeat = String.prototype.repeat || function (n) { return (n=n>>>0)===0 ? "" : this + this.repeat(n-1); }; | |
function helloNumber(a: number): string | |
{ | |
return "Hello world" + "!".repeat(a); | |
} | |
function helloString(a: string): string | |
{ | |
return "Hello " + a + "-san!"; | |
} | |
function hello(a: Sum<number, string>): string | |
{ | |
return a.elim(helloNumber, helloString); | |
} | |
console.log(hello(Left(7))); | |
console.log(hello(Right("Fujikido Kenji"))); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment