Skip to content

Instantly share code, notes, and snippets.

@wheaties
Last active April 17, 2017 19:08
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 wheaties/660d799d356a5aa0f53d96ce1c84e373 to your computer and use it in GitHub Desktop.
Save wheaties/660d799d356a5aa0f53d96ce1c84e373 to your computer and use it in GitHub Desktop.
FunctionK Continuation
import cats.~>
//what would happen if you tried to make a continuation based on natural transforms...
abstract class ContK[F[_], G[_], R]{ self =>
def apply(fg: F ~> G): G[R]
def map[B](f: R => B)(implicit fn: Functor[G]) = new ContK[F, G, B]{
def apply(fg: F ~> G) = fn.map(self(fg))(f)
}
def ap[B](cont: ContK[F, G, R => B])(implicit ap: Apply[G]) = new ContK[F, G, B]{
def apply(fg: F ~> G) = ap.ap(self(fg))(cont(fg))
}
def flatMap[B](f: R => ContK[F, G, B])(implicit b: Bind[G]) = new ContK[F, G, B]{
def apply(fg: F ~> G) = b.flatMap(self(fg)){ f(_)(fg) }
}
def mapK[H[_]](fh: F ~> H) = new ContK[H, G, R]{
def apply(hg: H ~> G) = self(fh andThen hg)
}
def flatMapK[H[_]](fc: F ~> ContK[H, G, ?]) = new ContK[H, G, R]{
def apply(hg: H ~> G) = self{
λ[FunctionK[F, G]](fa => fc(fa)(gh))
}
}
}
import cats.~>
//none of these are stack safe
abstract class IndexedContK[F[_], I[_], G[_], R]{ self =>
def apply(fig: F ~> I): G[R]
def map[B](f: R => B)(implicit fn: Functor[G]) = new IndexedContK[F, I, G, B]{
def apply(fig: F ~> I) = fn.map(self(fig))(f)
}
def ap[B](cont: IndexedContK[F, I, G, R => B])(implicit ap: Apply[G]) = new IndexedContK[F, I, G, B]{
def apply(fig: F ~> G) = ap.ap(self(fig))(cont(fig))
}
def flatMap[B](f: R => IndexedContK[F, I, G, B])(implicit b: Bind[G]) = new IndexedContK[F, I, G, B]{
def apply(fig: F ~> I) = b.flatMap(self(fig)){ f(_)(fig) }
}
def mapK[H[_]](fh: F ~> H) = new IndexedContK[H, I, G, R]{
def apply(hig: H ~> I) = self(fh andThen hig)
}
def flatMapK[H[_]](fc: F ~> IndexedContK[H, I, G, ?]) = new IndexedContK[H, I, G, R]{
def apply(hig: H ~> I) = self{
λ[FunctionK[F, I]](fa => fc(fa)(hig))
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment