Skip to content

Instantly share code, notes, and snippets.

@thautwarm
Created December 12, 2018 03:29
Show Gist options
  • Save thautwarm/9bfd2127763b5860d83cd312e3380d02 to your computer and use it in GitHub Desktop.
Save thautwarm/9bfd2127763b5860d83cd312e3380d02 to your computer and use it in GitHub Desktop.
higher kinded types implementation
interface HKT<K, T>{
}
interface Monad<M> {
bind: <A, B>(m: HKT<M, A>, k: (a: A) => HKT<M, B>) => HKT<M, B>
return: <A>(a: A) => HKT<M, A>
// ret$: <A>(m: (a: A) => HKT<M, A>) => HKT<M, A>
}
class Maybe implements Monad<Maybe> {
bind<A, B>(m: HKT<Maybe, A>, k: (a: A) => HKT<Maybe, B>): HKT<Maybe, B>{
if (m instanceof Some){
let mm = m as Some<A>
return k(mm.content)
}
return new None<A>()
}
return<A>(a: A): HKT<Maybe, A>{
return new Some(a)
}
}
class Some<A> implements HKT<Maybe, A>{
content: A
constructor(a: A){
this.content = a
}
}
class None<A> implements HKT<Maybe, A>{
constructor(){}
}
let m = new Some(1) as HKT<Maybe, number>
function bind<M>(m: Monad<M>): <A>(ma: HKT<M, A>) => <B>(k: (a: A) => HKT<M, B>) => HKT<M, B> {
return ma => k => m.bind(m, k)
}
let f = bind(new Maybe())
let k: (_:number) => HKT<Maybe, number> = (x: number) => new Some(x + 1) as HKT<Maybe, number>
let f2 = f(m)(k)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment