Skip to content

Instantly share code, notes, and snippets.

@retronym
Created December 3, 2009 12:53
Show Gist options
  • Save retronym/248134 to your computer and use it in GitHub Desktop.
Save retronym/248134 to your computer and use it in GitHub Desktop.
class Scratch
trait PartialApply1Of2[T[_, _], A] {
type Apply[B] = T[A, B]
type Flip[B] = T[B, A]
}
trait Cofunctor[F[_]] {
def comap[A, B](r: F[A], f: B => A): F[B]
}
object Cofunctor {
implicit def `(_ => X) ➝ Cofunctor`[X]: Cofunctor[PartialApply1Of2[Function1, X]#Flip] = new Cofunctor[PartialApply1Of2[Function1, X]#Flip] {
def comap[A, B](r: A => X, f: B => A) = r compose f
}
}
trait Functor[F[_]] {
def fmap[A, B](a: F[A], f: A => B): F[B]
}
object Functor {
implicit def `(X => _) ➝ Functor`[X]: Functor[PartialApply1Of2[Function1, X]#Apply] = new Functor[PartialApply1Of2[Function1, X]#Apply] {
def fmap[A, B](r: X => A, f: A => B) = f compose r
}
implicit val ListFunctor: Functor[List] = new Functor[List] {
def fmap[A, B](r: List[A], f: A => B) = r map f
}
}
sealed trait MA[M[_], A] {
val v: M[A]
def ∙[B](f: B => A)(implicit t: Cofunctor[M]) = t.comap(v, f)
def ∘[B](f: A => B)(implicit t: Functor[M]) = t.fmap(v, f)
}
trait MAsLow {
def maImplicit[M[_], A](a: M[A]): MA[M, A] = new MA[M, A] {
val v = a
}
}
trait MAs extends MAsLow {
def ma[M[_], A](a: M[A]): MA[M, A] = new MA[M, A] {
val v = a
}
implicit def `(_ => A) ➝ MA`[A, R](f: R => A): MA[PartialApply1Of2[Function1, A]#Flip, R] = ma[PartialApply1Of2[Function1, A]#Flip, R](f)
//
implicit def `(R => _) ➝ MA`[A, R](f: A => R): MA[PartialApply1Of2[Function1, A]#Apply, R] = ma[PartialApply1Of2[Function1, A]#Apply, R](f)
// Seq[A] implements Function1[Int, A]. Without this, Function1FlipMA would be used.
implicit def SeqMA[M[_] <: Seq[_], A](l: M[A]): MA[M, A] = ma[M, A](l)
}
////
object Example extends MAs {
def main(args: Array[String]) {
{
val f: Int => Int = (3 +)
println(List(1, 2, 3) ∘ f)
// List(3, 4, 4, 5, 5)
println(List(1, 2, 3, 4, 5) map (f ∙ ((_: Int) / 2)))
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment