Skip to content

Instantly share code, notes, and snippets.

@Willmo36
Created May 6, 2021 09:28
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save Willmo36/870887a97a17881b9f265d03f5d59315 to your computer and use it in GitHub Desktop.
Save Willmo36/870887a97a17881b9f265d03f5d59315 to your computer and use it in GitHub Desktop.
TypeScript GADT
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