Skip to content

Instantly share code, notes, and snippets.

@Horusiath
Created October 21, 2016 15:23
Show Gist options
  • Save Horusiath/8d321e34d23f75d3f3b6aebbd4dc4143 to your computer and use it in GitHub Desktop.
Save Horusiath/8d321e34d23f75d3f3b6aebbd4dc4143 to your computer and use it in GitHub Desktop.
HLists and HMaps in typescript
// HList
class HList { }
class HNil extends HList {
static readonly instance = new HNil();
private constructor() {
super();
}
}
class HCons<Value, Next extends HList> extends HList {
constructor(readonly value: Value, readonly next: Next) {
super()
}
}
function hcons<V, Next extends HList>(value: V, next: Next) { return new HCons<V, Next>(value, next); }
const hnil = HNil.instance;
// sample
var t = hcons(1, hcons("lol", hcons(true, hnil))); // t: HCons<number, HCons<string, HCons<boolean, HNil>>>
// HMap
interface Pair<Key, Val> {
key: Key;
value: Val
}
function hmap<K, V, N extends HList>(key: K, value: V, next: N): HCons<Pair<K,V>, N> { return hcons({key:key, value: value}, next); }
//sample
var map = hmap<"a", number, HCons<Pair<"b", boolean>, HNil>>("a", 1, hmap<"b", boolean, HNil>("b", true, hnil));
// map: HCons<Pair<"a", number>, HCons<Pair<"b", boolean>, HNil>>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment