daily pastebin goal
65%
SHARE
TWEET

Untitled

a guest May 16th, 2018 106 Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. class Scratch
  2.  
  3. trait PartialApply1Of2[T[_, _], A] {
  4.   type Apply[B] = T[A, B]
  5.   type Flip[B] = T[B, A]
  6. }
  7.  
  8. trait Cofunctor[F[_]] {
  9.   def comap[A, B](r: F[A], f: B => A): F[B]
  10. }
  11.  
  12. object Cofunctor {
  13.   implicit def `(_ => X) ➝ Cofunctor`[X]: Cofunctor[PartialApply1Of2[Function1, X]#Flip] = new Cofunctor[PartialApply1Of2[Function1, X]#Flip] {
  14.     def comap[A, B](r: A => X, f: B => A) = r compose f
  15.   }
  16. }
  17.  
  18. trait Functor[F[_]] {
  19.   def fmap[A, B](a: F[A], f: A => B): F[B]
  20. }
  21.  
  22. object Functor {
  23.   implicit def `(X => _) ➝ Functor`[X]: Functor[PartialApply1Of2[Function1, X]#Apply] = new Functor[PartialApply1Of2[Function1, X]#Apply] {
  24.     def fmap[A, B](r: X => A, f: A => B) = f compose r
  25.   }
  26.  
  27.   implicit val ListFunctor: Functor[List] = new Functor[List] {
  28.     def fmap[A, B](r: List[A], f: A => B) = r map f
  29.   }
  30. }
  31.  
  32. sealed trait MA[M[_], A] {
  33.   val v: M[A]
  34.  
  35.   def ∙[B](f: B => A)(implicit t: Cofunctor[M]) = t.comap(v, f)
  36.  
  37.   def ∘[B](f: A => B)(implicit t: Functor[M]) = t.fmap(v, f)
  38. }
  39.  
  40. trait MAsLow {
  41.   def maImplicit[M[_], A](a: M[A]): MA[M, A] = new MA[M, A] {
  42.     val v = a
  43.   }
  44. }
  45.  
  46. trait MAs extends MAsLow {
  47.   def ma[M[_], A](a: M[A]): MA[M, A] = new MA[M, A] {
  48.     val v = a
  49.   }
  50.  
  51.   implicit def `(_ => A) ➝ MA`[A, R](f: R => A): MA[PartialApply1Of2[Function1, A]#Flip, R] = ma[PartialApply1Of2[Function1, A]#Flip, R](f)
  52.   //
  53.   implicit def `(R => _) ➝ MA`[A, R](f: A => R): MA[PartialApply1Of2[Function1, A]#Apply, R] = ma[PartialApply1Of2[Function1, A]#Apply, R](f)
  54.  
  55.   //   Seq[A] implements Function1[Int, A]. Without this, Function1FlipMA would be used.
  56.   implicit def SeqMA[M[_] <: Seq[_], A](l: M[A]): MA[M, A] = ma[M, A](l)
  57. }
  58.  
  59. ////
  60.  
  61. object Example extends MAs {
  62.   def main(args: Array[String]) {
  63.     {
  64.       val f: Int => Int = (3 +)
  65.  
  66.       println(List(1, 2, 3) ∘ f)
  67.  
  68.       // List(3, 4, 4, 5, 5)
  69.       println(List(1, 2, 3, 4, 5) map (f ∙ ((_: Int) / 2)))
  70.     }
  71.   }
  72. }
RAW Paste Data
We use cookies for various purposes including analytics. By continuing to use Pastebin, you agree to our use of cookies as described in the Cookies Policy. OK, I Understand
 
Top