Created
May 6, 2021 09:28
-
-
Save Willmo36/870887a97a17881b9f265d03f5d59315 to your computer and use it in GitHub Desktop.
TypeScript GADT
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
function identity<T>(t:T):T{return t}; | |
class NumExpr<A> { | |
readonly _tag = "num"; | |
constructor (readonly value: number, readonly proof: (v: number) => A) {} | |
} | |
class StringExpr<A> { | |
readonly _tag = "str" | |
constructor (readonly value: string, readonly proof: (v: string) => A) {} | |
} | |
type Expr<A> = NumExpr<A> | StringExpr<A>; | |
const mkNum = (n: number) => new NumExpr(n, identity); | |
const mkStr = (s: string) => new StringExpr(s, identity); | |
// We can write evaluate generically, that's the point? | |
function evaluate<A>(exp: Expr<A>): A { | |
if(exp._tag === "num") { | |
return exp.proof(exp.value); | |
} | |
else { | |
return exp.proof(exp.value); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment