andyscott / scala_typeclassopedia

Patterns from category theory and abstract algebra in Scala

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

Scala typeclassopedia

Abstract Algebra

Category Theory

Category Theory

Functor (Covariant Functor)

Abstraction for type constructor (type with "hole", type parameter) that can be mapped over.

Containers (List, Tree, Option) can apply given function to every element in the collection. Computation effects (Option - may not have value, List - may have multiple values, Either/Validated - may contain value or error) can apply function to a value inside this effect without changing the effect.

trait Functor[F[_]] {
  def map[A,B](a: F[A])(f: A => B): F[B]
}
  • Functor Laws:
  1. identify: xs.map(identity) == xs
  2. composition: xs.map(f).map(g) == xs.map(x => g(f(x))

If Functor satisfy fist law then it also satisfy second law: (Haskell) The second Functor law is redundant - David Luposchainsky if we don't include bottom values - (Haskell) contrexample using undefined.

  • Instances can be implemented for: List, Vector, Option, Either, Validated, Tuple1, Tuple2, Function

  • Functor must preserve structure, so Set is not a Functor (map constant function would change the structure).

  • Derived methods of Functor:

def lift[A, B](f: A => B): F[A] => F[B] // lift regular function to function inside container
def fproduct[A, B](fa: F[A])(f: A => B): F[(A, B)] // zip elements with result after applying f
def as[A, B](fa: F[A], b: B): F[B] // replace every element with b
def void[A](fa: F[A]): F[Unit] // clear preserving structure
def tupleLeft[A, B](fa: F[A], b: B): F[(B, A)]
def tupleRight[A, B](fa: F[A], b: B): F[(A, B)]
def widen[A, B >: A](fa: F[A]): F[B]

Apply

Apply is a Functor that can apply function already inside container to container of arguments.

Apply is a weaker version of Applicative that cannot put value inside effetc F.

trait Apply[F[_]] extends Functor[F] {
  def ap[A, B](ff: F[A => B])(fa: F[A]): F[B]
}
  • Derived methods
def apply2[A, B, Z]   (fa: F[A], fb: F[B])          (ff: F[(A,B) => Z]): F[Z]
def apply3[A, B, C, Z](fa: F[A], fb: F[B], fc: F[C])(ff: F[(A,B,C) => Z]): F[Z]
// ...

def map2[A , B, Z]  (fa: F[A], fb: F[B])          (f: (A, B) => Z):    F[Z]
def map3[A, B, C, Z](fa: F[A], fb: F[B], fc: F[C])(f: (A, B, C) => Z): F[Z]
// ...

def tuple2[A, B]   (fa: F[A], fb: F[B]):           F[(A, B)]
def tuple3[A, B, C](fa: F[A], fb: F[B], fc: F[C]): F[(A, B, C)]
// ...

def product[A,B](fa: F[A], fb: F[B]): F[(A, B)]
def flip[A, B](ff: F[A => B]): F[A] => F[B]

Applicative (Applicative Functor)

Applicative Functor is a Functor that can:

  • apply function already inside container to container of arguments (so it is Apply)
  • put value into container (lift into effect)
trait Applicative[F[_]] extends Apply[F] {
  def pure[A](value: A): F[A]
}
  • Applicative Laws:
  1. identify: xs.apply(pure(identity)) == xs apply identify function lifted inside effect does nothing
  2. homomorphism: pure(a).apply(pure(f)) == pure(f(a)) lifting value a and applying lifted function f is the same as apply function to this value and then lift result
  3. interchange: pure(a).apply(ff) == ff.apply(pure(f => f(a))) where ff: F[A => B]
  4. map: fa.map(f) == fa.apply(pure(f))
  • Derived methods - see Apply
  • Applicatives can be composed
  • Minimal set of methods to implement Applicative (other methods can be derived from them):
    • map2, pure
    • apply, pure
  • Resources:

Monad

We add to Apply ability flatMap that can join two computations and use the output from previous computations to decide what computations to run next.

trait Monad[F[_]] extends Apply[F] {
  def pure[A](value: A): F[A]
  def flatMap[A, B](fa: F[A])(f: A => F[B]): F[B]
}
  • Monad Laws:

    1. flatmap associativity: fa.flatMap(f).flatMap(g) == fa.flatMap(a => f(a).flatMap(b => g(b))
    2. left identity: pure(a).flatMap(f) == f(a)
    3. right identity: fa.flatMap(a => pure(a)) == fa
  • Minimal set of methods to implement Monad (others can be derived using them):

    • pure, flatMap
    • pure, flatten, map
    • pure, flatten, apply
    • pure, flatten, map2
  • Derived methods:

def flatten[A](ffa: F[F[A]]): F[A]
def sequence[G[_], A](as: G[F[A]])(implicit G: Traverse[G]): F[G[A]]
def traverse[A, G[_], B](value: G[A])(f: A => F[B])(implicit G: Traverse[G]): F[G[B]]
def replicateA[A](n: Int, fa: F[A]): F[List[A]]
def unit: F[Unit] // put under effect ()
def factor[A, B](ma: F[A], mb: F[B]): F[(A, B)]

Reader

Wrapper around function from given type. Input type can be seen as some configuration required to produce result.

case class Reader[-In, +R](run: In => R) {
  def map[R2](f: R => R2): Reader[In, R2] =
    Reader(run andThen f)

  def flatMap[R2, In2 <: In](f: R => Reader[In2, R2]): Reader[In2, R2] =
    Reader(x => f(run(x)).run(x))
}

Writer

  • Resources
    • Monadic Logging and You - Martin Snyder (video)
    • The Writer Monad using Scala (example) - Tony Morris: blog post

State

  • Resources
    • Towards an Effect System in Scala, Part 1: ST Monad (blog post)
    • Scalaz State Monad - Michael Pilquist (video)
    • Memoisation with State using Scala - Tony Morris (blog post)
    • Monads to Machine Code - Stephen Diehl: (blog post) explore JIT compilation and LLVM using IO Monad and State Monad

IO related monads

IO Monad

Bifunctor IO (BIO)

RIO Monad (Reader + IO)

TRIO (RIO Monad + Bifunctor IO)

RWS Monad

Logic Monad, Prompt Monad, Failure Monad

Type-Indexed Monads

ContT (Continuation Monad)

Reverse State Monad

Tardis (Bidirectional State Monad)

Contravariant (Contravariant Functor)

trait Contravariant[F[_]] {
  def contramap[A, B](f: B => A): F[A] => F[B]
}

Divide (Contravariant Apply)

trait Divide[F[_]] extends Contravariant[F] {
  def divide[A, B, C](fa: F[A], fb: F[B])(f: C => (A, B)): F[C]
}
  • Laws: let def delta[A]: A => (A, A) = a => (a, a)
    1. composition divide(divide(a1, a2)(delta), a3)(delta) == divide(a1, divide(a2, a3),(delta))(delta)
  • Derived methods:
def divide1[A1, Z]    (a1: F[A1])           (f: Z => A1): F[Z] // contramap
def divide2[A1, A2, Z](a1: F[A1], a2: F[A2])(f: Z => (A1, A2)): F[Z]
// ...
def tuple2[A1, A2]    (a1: F[A1], a2: F[A2]):            F[(A1, A2)]
def tuple3[A1, A2, A3](a1: F[A1], a2: F[A2], a3: F[A3]): F[(A1, A2, A3)]
// ...
def deriving2[A1, A2, Z](f: Z => (A1, A2))(implicit a1: F[A1], a2: F[A2]): F[Z]
def deriving3[A1, A2, A3, Z](f: Z => (A1, A2, A3))(implicit a1: F[A1], a2: F[A2], a3: F[A3]): F[Z]
// ...
  • Resources
    • Discrimination is Wrong: Improving Productivity - Edward Kmett (video)
    • scalaz (src)

Divisible (Contravariant Applicative)

trait Divisible[F[_]] extends Divide[F] {
  def conquer[A]: F[A]
}
  • Laws: let def delta[A]: A => (A, A) = a => (a, a)
    1. composition divide(divide(a1, a2)(delta), a3)(delta) == divide(a1, divide(a2, a3),(delta))(delta)
    2. right identity: divide(fa, conquer)(delta) == fa
    3. left identity: divide(conquer, fa)(delta) == fa
  • Resources

Bifunctor

Abstracts over type constructor with 2 "holes". Represents two independent functors:

trait Bifunctor[F[_, _]] {
  def bimap[A, B, C, D](fab: F[A, B])(f: A => C, g: B => D): F[C, D]
}
  • Bifunctor Laws
  1. identity xs.bimap(identity, identity) == xs bimap with two identify function does nothing
  2. composition xs.bimap(f, h).bimap(g,i) == xs.bimap(x => g(f(x), x => h(i(x)) you can bimap using f and h and then bimap using g and i or bimap once using composition Second law is automatically fulfilled if the first law holds.
  • Alternatively can be specified by providing
def leftMap[A, B, C](fab: F[A, B])(f: A => C): F[C, B]
def rightMap[A, B, D](fab: F[A, B])(g: B => D): F[A, D]

In that case identity law must hold for both functions: 3. identity xs.leftMap(identity) == xs leftMap with identify function does nothing 4. identity xs.rightMap(identity) == xs rightMap with identify function does nothing If leftMap and rightMap and bimap are specified then additional lwa must be fullfilled: 5. xs.bimap(f, g) == xs.leftMap(f).rightMap(g)

  • Derived methods
def leftMap[A, B, C](fab: F[A, B])(f: A => C): F[C, B]
def rightMap[A, B, D](fab: F[A, B])(g: B => D): F[A, D]
def leftFunctor[X]: Functor[F[?, X]]
def rightFunctor[X]: Functor[F[X, ?]]
def umap[A, B](faa: F[A, A])(f: A => B): F[B, B]
def widen[A, B, C >: A, D >: B](fab: F[A, B]): F[C, D]

Invariant (Invariant Functor, Exponential Functor)

Functor that can create covariant functor (by passing identity as g) or contravariant functor (by passing identity to f)

trait Invariant[F[_]] {
  def imap[A, B](fa: F[A])(f: A => B)(g: B => A): F[B]
}
  • Resources

Comonad

Abstraction for type with one hole that allows:

  • map over (extends Functor)
  • get current value
  • duplicate one layer of abstraction It is dual to Monad (Monad allow to put value in and collapse one layer).
trait Comonad[C[_]] extends Functor[C] {
  def extract[A](ca: C[A]): A // counit
  def duplicate[A](ca: C[A]): C[C[A]] // coflatten
  def extend[A, B](ca: C[A])(f: C[A] => B): C[B] = map(duplicate(ca))(f) // coflatMap, cobind
}

If we define extract and extend:

  1. fa.extend(_.extract) == fa
  2. fa.extend(f).extract == f(fa)
  3. fa.extend(f).extend(g) == fa.extend(a => g(a.extend(f)))

If we define comonad using map, extract and duplicate: 3. fa.duplicate.extract == fa 4. fa.duplicate.map(_.extract) == fa 5. fa.duplicate.duplicate == fa.duplicate.map(_.duplicate)

And if we provide implementation for both duplicate and extend: 6. fa.extend(f) == fa.duplicate.map(f) 7. fa.duplicate == fa.extend(identity) 8. fa.map(h) == fa.extend(faInner => h(faInner.extract))

The definitions of laws in Cats src Comonad , Cats src Coflatmap and Haskell Control.Comonad.

  • Derived methods:
 def extend[A, B](ca: C[A])(f: C[A] => B): C[B] = map(duplicate(ca))(f) // coFlatMap

Method extend can be use to chain oparations on comonads - this is called coKleisli composition.

Coreader (Env comonad, Product comonad)

Wrap value of type A with some context R.

case class CoReader[R, A](extract: A, ask: R) {
  def map[B](f: A => B): CoReader[R, B] = CoReader(f(extract), ask)
  def duplicate: CoReader[R, CoReader[R, A]] = CoReader(this, ask)
}

Cowriter

It is like Writer monad, combines all logs (using Monid) when they are ready.

case class Cowriter[W, A](tell: W => A)(implicit m: Monoid[W]) {
  def extract: A = tell(m.empty)
  def duplicate: Cowriter[W, Cowriter[W, A]] = Cowriter( w1 =>
    Cowriter( w2 =>
      tell(m.append(w1, w2))
    )
  )
  def map[B](f: A => B) = Cowriter(tell andThen f)
}
  • Resources
    • Scala Comonad Tutorial, Part 1 - Rúnar Bjarnason (blog post)

Bimonad

Combine power of Monad and Comonad with additiona laws that tie together Monad and Comonad methods

trait Bimonad[T] extends Monad[T] with Comonad[T]
  • They simplify resolution of implicits for things that are Monad and Comonad

Resources:

Foldable

Given definition of foldLeft (eager, left to right0) and foldRight (lazi, right to left) provide additional way to fold Monoid.

trait Foldable[F[_]]  {
  def foldLeft[A, B](fa: F[A], b: B)(f: (B, A) => B): B
  def foldRight[A, B](fa: F[A], z: => B)(f: (A, => B) => B): B
}
  • Laws: no. You can define condition that foldLeft and foldRight must be consistent.
  • Derived methods (are different for scalaz and Cats):
def foldMap[A, B](fa: F[A])(f: A => B)(implicit B: Monoid[B]): B
def foldM    [G[_], A, B](fa: F[A], z: B)(f: (B, A) => G[B])(implicit G: Monad[G]): G[B] // foldRightM
def foldLeftM[G[_], A, B](fa: F[A], z: B)(f: (B, A) => G[B])(implicit G: Monad[G]): G[B]
def find[A](fa: F[A])(f: A => Boolean): Option[A] // findLeft findRight
def forall[A](fa: F[A])(p: A => Boolean): Boolean // all
def exists[A](fa: F[A])(p: A => Boolean): Boolean // any
def isEmpty[A](fa: F[A]): Boolean // empty
def get[A](fa: F[A])(idx: Long): Option[A] // index
def size[A](fa: F[A]): Long // length
def toList[A](fa: F[A]): List[A]
def intercalate[A](fa: F[A], a: A)(implicit A: Monoid[A]): A
def existsM[G[_], A](fa: F[A])(p: A => G[Boolean])(implicit G: Monad[G]): G[Boolean] // anyM
def forallM[G[_], A](fa: F[A])(p: A => G[Boolean])(implicit G: Monad[G]): G[Boolean] // allM

// Cats specific
def filter_[A](fa: F[A])(p: A => Boolean): List[A]
def takeWhile_[A](fa: F[A])(p: A => Boolean): List[A]
def dropWhile_[A](fa: F[A])(p: A => Boolean): List[A]
def nonEmpty[A](fa: F[A]): Boolean
def foldMapM[G[_], A, B](fa: F[A])(f: A => G[B])(implicit G: Monad[G], B: Monoid[B]): G[B]
def traverse_[G[_], A, B](fa: F[A])(f: A => G[B])(implicit G: Applicative[G]): G[Unit]
def sequence_[G[_]: Applicative, A](fga: F[G[A]]): G[Unit]
def foldK[G[_], A](fga: F[G[A]])(implicit G: MonoidK[G]): G[A]

// scalaz specific
def filterLength[A](fa: F[A])(f: A => Boolean): Int
def maximum[A: Order](fa: F[A]): Option[A]
def maximumOf[A, B: Order](fa: F[A])(f: A => B): Option[B]
def minimum[A: Order](fa: F[A]): Option[A]
def minimumOf[A, B: Order](fa: F[A])(f: A => B): Option[B]
def splitWith[A](fa: F[A])(p: A => Boolean): List[NonEmptyList[A]]
def splitBy[A, B: Equal](fa: F[A])(f: A => B): IList[(B, NonEmptyList[A])]
def selectSplit[A](fa: F[A])(p: A => Boolean): List[NonEmptyList[A]]
def distinct[A](fa: F[A])(implicit A: Order[A]): IList[A]

Traverse

Functor with method traverse and folding functions from Foldable.

trait Traverse[F[_]] extends Functor[F] with Foldable[F] {
  def traverse[G[_]: Applicative, A, B](fa: F[A])(f: A => G[B]): G[F[B]]
}
def sequence[G[_]:Applicative,A](fga: F[G[A]]): G[F[A]]
def zipWithIndex[A](fa: F[A]): F[(A, Int)] // indexed
// ... other helper functions are different for scalaz and cats
  • Traverse are composable Distributive (scalaz src) it require only Functor (and Traverse require Applicative)
trait Distributive[F[_]] extends Functor[F] {
   def distribute[G[_]:Functor,A,B](fa: G[A])(f: A => F[B]): F[G[B]]
   def cosequence[G[_]:Functor,A](fa: G[F[A]]): F[G[A]]
}

SemigroupK (Plus)

Semigroup that abstracts over type constructor F. Fo any proper type A can produce Semigroup for F[A].

trait SemigroupK[F[_]] {
  def combineK[A](x: F[A], y: F[A]): F[A]  // plus
  def algebra[A]: Semigroup[F[A]] //  semigroup
}
  • SemigroupK can compose

  • Resources:

    • Scalaz (src)
    • Cats docs src
    • FSiS 6 - SemigroupK, MonoidK, MonadFilter, MonadCombine - Michael Pilquist (video)

MonoidK (PlusEmpty)

Monoid that abstract over type constructor F. For any proper type A can produce Monoid for F[A].

trait MonoidK[F[_]] extends SemigroupK[F] {
  def empty[A]: F[A]
  override def algebra[A]: Monoid[F[A]] // monoid
}
  • MonoidK can compose

  • Resources:

TraverseEmpty

Monad Transformers (OptionT EitherT ReaderT)

"Monad transformers just aren’t practical in Scala." John A De Goes

Natural transformation (FunctionK)

Represent mappings between two functors.

trait NaturalTransf[F[_], G[_]] {
  def apply[A](fa: F[A]): G[A]
}

Free constructions

abstraction free construction
Monoid List, Vector
Functor Yoneda, Coyoneda, Density, Codensity, Right Kan Extension, Left Kan Extension, Day Convolution
Applicative FreeApplicative
Alternative Free Alternative
Monad Free Monads, Codensity, Right Kan Extension
Comonad CoFree, Density
Profunctor Profunctor CoYoneda, Profunctor Yoneda, Tambara, Pastro, Cotambara, Copastro, TambaraSum, PastroSum, CotambaraSum, CopastroSum, Closure, Environment, CofreeTraversing, FreeTraversing, Traversing
ProfunctorFunctor Profunctor CoYoneda, Profunctor Yoneda, Tambara, Pastro, Cotambara, Copastro, TambaraSum, PastroSum, CotambaraSum, CopastroSum, Closure, Environment, CofreeTraversing, FreeTraversing
ProfunctorMonad Pastro, Copastro, PastroSum, CopastroSum, Environment, FreeTraversing
ProfunctorComonad Tambara, Cotambara, TambaraSum, CotambaraSum, Closure, CofreeTraversing
Strong Tambara, Pastro, Traversing
Costrong Cotambara, Copastro
Choice TambaraSum, PastroSum
Cochoice CotambaraSum, CopastroSum, Traversing
Closed Closure, Environment
Traversing CofreeTraversing, FreeTraversing
Arrow Free Arrow

Free Applicative

Free Monads

ADT (sometimes implemented using Fix point data type) that form a Monad without any other conditions:

sealed trait Free[F[_],A]
case class Return[F[_],A](a: A) extends Free[F,A]
case class Suspend[F[_],A](s: F[Free[F,A]]) extends Free[F,A]

Cofree

Create comonad for any given type A. It is based on rose tree (multiple nodes, value in each node) where List is replaced with any Functor F. Functor F dedicdes how Cofree comonad is branching.

case class Cofree[A, F[_]](extract: A, sub: F[Cofree[A, F]])(implicit functor: Functor[F]) {
  def map[B](f: A => B): Cofree[B, F] = Cofree(f(extract), functor.map(sub)(_.map(f)))
  def duplicate: Cofree[Cofree[A, F], F] = Cofree(this, functor.map(sub)(_.duplicate))
  def extend[B](f: Cofree[A, F] => B): Cofree[B, F] = duplicate.map(f) // coKleisi composition
}

Free Alternative

Representable & Adjunctions

Representable

// TODO Haskell extends Distrivutive, Scalaz require F to be Functor
trait Representable[F[_], Rep] {
  def tabulate[X](f: Rep => X): F[X]
  def index[X](fx: F[X])(f: Rep): X
}

Adjunction

Adjunction[F,B] spacify relation between two Functors (There is natural transformation between composition of those two functors and identity.) We say that F is left adjoint to G.

trait Adjunction[F[_], G[_]] {
  def left[A, B](f: F[A] => B): A => G[B]
  def right[A, B](f: A => G[B]): F[A] => B
}

Adjunction can be defined between Reader monad and Coreader comonad.

(Co)Yoneda & (Co)Density & Kan Extensions

Yoneda

Construction that abstract over type constructor and allow to effectively stack computations.

In Category Theory

Yoneda Lemma states that: [C,Set](C(a,-),F) ~ Fa Set of natural transformations from C to Set of the Hom functor C(a,-) to Functor F: C -> Set is isomorphic to Fa

It is possible to formulate Yoneda Lemma in terms of Ends, and we get Ninja Yoneda Lemma: ∫ Set(C(a,x),F(x)) ~ Fa

That corresponds to:

def yoneda[R](cax: A => X, fx F[X]) ~ F[A]

trait Yoneda[F[_], A] {
  def run[R](f: A => R): F[R]
}
  • we need Functor instance for F to create instance of Yoned for F
def liftYoneda[F[_], A](fa: F[A])(implicit FunctorF: Functor[F]): Yoneda[F, A] =
  new Yoneda[F, A] {
    def run[R2](f: A => R2): F[R2] = FunctorF.map(fa)(f)
  }
  • we don't need the fact that F is a Functor to go back to F
def lowerYoneda[F[_], A](y: Yoneda[F, A]): F[A] = y.run(identity[A])
  • we can define Functor instance without any requirement on F:
def yonedaFunctor[F[_]]: Functor[Yoneda[F, ?]] =
  new Functor[Yoneda[F, ?]] {
    def map[A, B](fa: Yoneda[F, A])(f: A => B): Yoneda[F, B] =
      new Yoneda[F, B] {
        def run[C](f2: B => C): F[C] = fa.run(f andThen f2)
      }
  }

Coyoneda

Rúnar in Free Monads and the Yoneda Lemma describe this type as a proof that: "if we have a type B, a function of type (B => A) for some type A, and a value of type F[B] for some functor F, then we certainly have a value of type F[A]"

This result from Category Theory allow us to perform Coyoneda Trick:

If we have following type:

trait Coyoneda[F[_], A] {
  type B
  def f: B => A
  def fb: F[B]
}

then type constructor F can be lifted to Coyoneda

def liftCoyoneda[F[_], A](fa: F[A]): Coyoneda[F, A]

we can map over lifted constructor F without any requirements on F. So Coyoneda is a Free Functor:

implicit def coyoFunctor[F[_]]: Functor[Coyoneda[F, ?]] = new Functor[Coyoneda[F, ?]] {
  def map[A, AA](fa: Coyoneda[F, A])(ff: A => AA): Coyoneda[F, AA] = new Coyoneda[F, AA] {
    type B = fa.B
    def f: B => AA = fa.f andThen ff
    def fb: F[B] = fa.fb
  }
}

We even can change the oryginal type of F

def hoistCoyoneda[F[_], G[_], A, C](fab : NaturalTransf[F,G])(coyo: Coyoneda[F, A]): Coyoneda[G, A] =
  new Coyoneda[G, A] {
    type B = coyo.B
    def f: B => A = coyo.f
    def fb: G[B] = fab(coyo.fb)
  }

Finally to get back from Coyoneda fantazy land to reality of F, we need a proof that it is a Functor:

def lowerCoyoneda(implicit fun: Functor[F]): F[A]

Right Kan extension

trait Ran[G[_], H[_], A] {
  def runRan[B](f: A => G[B]): H[B]
}
  • We can create functor for Ran without any requirements on G, H
def ranFunctor[G[_], H[_]]: Functor[Ran[G, H, ?]] =
    new Functor[Ran[G, H, ?]] {

      def map[A, B](fa: Ran[G, H, A])(f: A => B): Ran[G, H, B] =
        new Ran[G, H, B] {
          def runRan[C](f2: B => G[C]): H[C] =
            fa.runRan(f andThen f2)
        }
    }
  • We can define Monad for Ran without any requirements on G, H. Monad generated by Ran is Codensity.
def codensityMonad[F[_], A](ran: Ran[F, F, A]): Codensity[F, A] =
  new Codensity[F, A] {
    def run[B](f: A => F[B]): F[B] = ran.runRan(f)
  }

Left Kan Extension

trait Lan[F[_], H[_], A] {
  type B
  val hb: H[B]
  def f: F[B] => A
}
  • we can define Functor for it
def lanFunctor[F[_], H[_]]: Functor[Lan[F, H, ?]] = new Functor[Lan[F, H, ?]]() {
  def map[A, X](x: Lan[F, H, A])(fax: A => X): Lan[F, H, X] = {
    new Lan[F, H, X] {
      type B = x.B
      val hb: H[B] = x.hb
      def f: F[B] => X = x.f andThen fax
    }
  }
}

Density Comonad

Density is a Comonad that is simpler that Left Kan Extension. More precisely it is comonad formed by left Kan extension of a Functor along itself.)

trait Density[F[_], Y] { self =>
  type X
  val fb: F[X]
  def f: F[X] => Y
  
  def densityToLan: Lan[F,F,Y] = new Lan[F,F,Y] {
   type B = X
   val hb: F[B] = fb
   def f: F[B] => Y = self.f
  }
}

object Density {
  def apply[F[_], A, B](kba: F[B] => A, kb: F[B]): Density[F, A] = new Density[F, A] {
    type X = B
    val fb: F[X] = kb
    def f: F[X] => A = kba
  }
}

Density form a Functor without any conditions of F so it is a Free Functor. Similar like Lan.

def functorInstance[K[_]]: Functor[Density[K, ?]] = new Functor[Density[K, ?]] {
  def map[A, B](x: Density[K, A])(fab: A => B): Density[K, B] = Density[K,B,x.X](x.f andThen fab, x.fb)
}

Density is a Comonad without any conditions of F so it is a Free Comonad.

def comonadInstance[K[_]]: Comonad[Density[K, ?]] = new Comonad[Density[K, ?]] {
  def extract[A](w: Density[K, A]): A = w.f(w.fb)
  def duplicate[A](wa: Density[K, A]): Density[K, Density[K, A]] =
    Density[K, Density[K, A], wa.X](kx => Density[K, A, wa.X](wa.f, kx), wa.fb)
  def map[A, B](x: Density[K, A])(f: A => B): Density[K, B] = x.map(f)
}

Codensity

Interface with flatMap'ish method:

trait Codensity[F[_], A] {
  def run[B](f: A => F[B]): F[B]
}

that gives us monad (without any requirement on F):

implicit def codensityMonad[G[_]]: Monad[Codensity[G, ?]] =
  new Monad[Codensity[G, ?]] {
    def map[A, B](fa: Codensity[G, A])(f: A => B): Codensity[G, B] =
      new Codensity[G, B] {
        def run[C](f2: B => G[C]): G[C] = fa.run(f andThen f2)
      }

    def unit[A](a: A): Codensity[G, A] =
      new Codensity[G, A] {
        def run[B](f: A => G[B]): G[B] = f(a)
      }

    def flatMap[A, B](c: Codensity[G, A])(f: A => Codensity[G, B]): Codensity[G, B] =
      new Codensity[G, B] {
        def run[C](f2: B => G[C]): G[C] = c.run(a => f(a).run(f2))
      }
  }

Functor Functor (FFunctor)

Functor that works on natural transformations rather than on regular types

trait FFunctor[FF[_]] {
  def ffmap[F[_],G[_]](nat: NaturalTransf[F,G]): FF[F] => FF[G]
}
  • Laws:

    • identity: ffmap id == id
    • composition: ffmap (eta . phi) = ffmap eta . ffmap phi
  • Resources

Monoidal Categories, Monoid Object

In Category Theory a Monoidal Category is a Category with a Bifuctor and morphisms that satisfy some laws (see gist for details).

trait MonoidalCategory[M[_, _], I] {
  val tensor: Bifunctor[M]
  val mcId: I

  def rho[A]    (mai: M[A,I]): A
  def rho_inv[A](a:   A):      M[A, I]

  def lambda[A]      (mia: M[I,A]): A
  def lambda_inv[A,B](a: A):        M[I, A]

  def alpha[A,B,C](    mabc: M[M[A,B], C]): M[A, M[B,C]]
  def alpha_inv[A,B,C](mabc: M[A, M[B,C]]): M[M[A,B], C]
}

We can create monoidal category where product (Tuple) is a bifunctor or an coproduct (Either).

Monoidal Categories are usefull if we consider category of endofunctors. If we develop concept of Monoid Object then it is possible to define Monads as Monoid Object in Monoidal Category of Endofunctors with Product as Bifunctor Applicative as Monoid Object in Monoidal Category of Endofunctors with Day convolution as Bifunctor

In category of Profunctors with Profunctor Product as Bifunctor the Monoid Ojbect is Arrow.

Day Convolution

Monads are monoids in a monoidal category of endofunctors. Applicative functors are also monoids in a monoidal category of endofunctors but as a tensor is used Day convolution.

There is nice intuition for Day convolution as generalization of one of Applicative Functor methods.

  • Haskell
data Day f g a where
  Day :: forall x y. (x -> y -> a) -> f x -> g y -> Day f g a
  • Scala
trait DayConvolution[F[_], G[_], A] {
  type X
  type Y
  val fx: F[X]
  val gy: G[Y]
  def xya: (X, Y) => A
}
  • There is various ways to create Day Convolution:
def day[F[_], G[_], A, B](fab: F[A => B], ga: G[A]): Day[F, G, B]
def intro1[F[_], A](fa: F[A]): Day[Id, F, A]
def intro2[F[_], A](fa: F[A]): Day[F, Id, A]
  • Day convolution can be transformed by mapping over last argument, applying natural transformation to one of type constructors, or swapping them
def map[B](f: A => B): Day[F, G, B]
def trans1[H[_]](nat: NaturalTransf[F, H]): Day[H, G, A]
def trans2[H[_]](nat: NaturalTransf[G, H]): Day[F, H, A]
def swapped: Day[G, F, A] = new Day[G, F, A]
  • There is various ways to collapse Day convolution into value in type constructor:
def elim1[F[_], A](d: Day[Id, F, A])(implicit FunF: Functor[F]): F[A]
def elim2[F[_], A](d: Day[F, Id, A])(implicit FunF: Functor[F]): F[A]
def dap[F[_], A](d: Day[F, F, A])(implicit AF: Applicative[F]): F[A]
  • We can define Functor instance without any conditions on type constructors (so it forms Functor for free like Coyoneda):
def functorDay[F[_], G[_]]: Functor[DayConvolution[F, G, ?]] = new Functor[DayConvolution[F, G, ?]] {
  def map[C, D](d: DayConvolution[F, G, C])(f: C => D): DayConvolution[F, G, D] =
    new DayConvolution[F, G, D] {
      type X = d.X
      type Y = d.Y
      val fx: F[X] = d.fx
      val gy: G[Y] = d.gy

      def xya: X => Y => D = x => y => f(d.xya(x)(y))
    }
}

Profunctor

Profunctor abstract over

  • type constructor with two holes P[_,_]
  • operation def dimap(preA: NewA => A, postB: B => NewB): P[A, B] => P[NewA, NewB] that given P[A,B] and two functions
  • apply first preA before first type of P (ast as contravariant functor)
  • apply second postB after second type of P (act as functor)

Alternatively we can define Profunctor not using dimap but using two separate functions:

  • def lmap(f: AA => A): P[A,C] => P[AA,C] = dimap(f,identity[C])
  • def rmap(f: B => BB): P[A,B] => P[A,BB] = dimap(identity[A], f)

Profunctors in Haskell were explored by sifpe at blog A Neighborhood of Infinity in post Profunctors in Haskell Implemented in Haskell: ekmett/profunctors

trait Profunctor[F[_, _]] {
  def dimap[A, B, C, D](fab: F[A, B])(f: C => A)(g: B => D): F[C, D]
}
  • Alternatively we can define functor using:
def lmap[A, B, C](fab: F[A, B])(f: C => A): F[C, B]
def rmap[A, B, C](fab: F[A, B])(f: B => C): F[A, C]
  • Most popular is instance for Function with 1 argument:
trait Profunctor[Function1] {
  def lmap[A,B,C](f: A => B): (B => C) => (A => C) = f andThen
  def rmap[A,B,C](f: B => C): (A => B) => (A => C) = f compose
}

Becasue Profunctors can be used as base to define Arrows therefore there are instances for Arrow like constructions like Kleisli

  • In Category Theroy: When we have Category C and D and D' the opposite category to D, then a Profunctor P is a Functor D' x C -> Set We write D -> C In category of types and functions we use only one category, so Profunctor P is C' x C => C

  • Laws:

  • if we define Profunctor using dimap:

    • dimap id id == id
    • dimap (f . g) (h . i) == dimap g h . dimap f i Second law we get for free by parametricity.
  • if specify lmap or rmap

    • lmap id == id
    • rmap id == id
    • lmap (f . g) == lmap g . lmap f
    • rmap (f . g) == rmap f . rmap g

Last two laws we get for free by parametricity.

  • if specify both (in addition to law for dimap and laws for lmap:
    • dimap f g == lmap f . rmap g

Star

Lift Functor into Profunctor "forward"

case class Star[F[_],D,C](runStar: D => F[C])

If F is a Functor then Star[F, ?, ?] is a Profunctor:

def profunctor[F[_]](implicit FF: Functor[F]): Profunctor[Star[F, ?,?]] = new Profunctor[Star[F, ?, ?]] {
  def dimap[X, Y, Z, W](ab: X => Y, cd: Z => W): Star[F, Y, Z] => Star[F, X, W] = bfc =>
    Star[F,X, W]{ x =>
      val f: Y => F[Z] = bfc.runStar
      val fz: F[Z] = f(ab(x))
      FF.map(fz)(cd)
    }
}

CoStar

Lift Functor into Profunctor "backwards"

case class Costar[F[_],D,C](runCostar: F[D] => C)

If F is a Functor then Costar[F, ?, ?] is a Profunctor

def profunctor[F[_]](FF: Functor[F]): Profunctor[Costar[F, ?, ?]] = new Profunctor[Costar[F, ?, ?]] {
  def dimap[A, B, C, D](ab: A => B, cd: C => D): Costar[F, B, C] => Costar[F, A, D] = fbc =>
    Costar{ fa =>
      val v: F[B] = FF.map(fa)(ab)
      val c: C = fbc.runCostar(v)
      cd(c)
    }
}

Strong Profunctor

Profunctor with additional method first that lift profunctor so it can run on first element of tuple.

For Profunctor of functions from A to B this operation just apply function to first element of tuple.

trait StrongProfunctor[P[_, _]] extends Profunctor[P] {
  def first[X,Y,Z](pab: P[X, Y]): P[(X, Z), (Y, Z)]
}
  • Laws in Haskell implementation of Strong Profunctor
    1. first == dimap(swap, swap) andThen second
    2. lmap(_.1) == rmap(_.1) andThen first
    3. lmap(second f) andThen first == rmap(second f) andThen first
    4. first . first ≡ dimap assoc unassoc . first
    5. second ≡ dimap swap swap . first
    6. lmap snd ≡ rmap snd . second
    7. lmap (first f) . second ≡ rmap (first f) . second
    8. second . second ≡ dimap unassoc assoc . second

where

assoc ((a,b),c) = (a,(b,c))
unassoc (a,(b,c)) = ((a,b),c)

In Notions of Computation as Monoids by Exequiel Rivas and Mauro Jaskelioff in 7.1 there are following laws:

  1. dimap identity pi (first a) = dimap pi id a
  2. first (first a) = dimap alphaInv alpha (first a)
  3. dimap (id × f) id (first a) = dimap id (id × f) (first a)
  • Derived methods:
def second[X,Y,Z](pab: P[X, Y]): P[(Z, X), (Z, Y)]
def uncurryStrong[P[_,_],A,B,C](pa: P[A, B => C])(S: Strong[P]): P[(A,B),C]

In Purescript implementation of Strong there are some more helper methods that use Category constraint for P.

  • Most common instance is Function with one argument:
val Function1Strong = new Strong[Function1] with Function1Profunctor {
  def first[X, Y, Z](f: Function1[X, Y]): Function1[(X,Z), (Y, Z)] = { case (x,z) => (f(x), z) }
}

it is possible to define instance for Kleisli arrow

Tambara

trait Tambara[P[_,_],A,B]{
  def runTambara[C]: P[(A,C),(B,C)]
}

Tambara is a Profunctor:

trait Profunctor[Tambara[P, ?, ?]] {
  def PP: Profunctor[P]

  def dimap[X, Y, Z, W](f: X => Y, g: Z => W): Tambara[P, Y, Z] => Tambara[P, X, W] = (tp : Tambara[P, Y, Z]) => new Tambara[P, X, W]{
   
    def runTambara[C]: P[(X, C), (W, C)] = {
      val fp: P[(Y,C),(Z,C)] => P[(X, C), (W, C)] = PP.dimap(
        Function1Strong.first[X, Y, C](f),
        Function1Strong.first[Z, W, C](g)
      )
      val p: P[(Y,C),(Z,C)] = tp.runTambara[C]
      fp(p)
    }
  }
}

It is also FunctorProfunctor:

def promap[P[_, _], Q[_, _]](f: DinaturalTransformation[P, Q])(implicit PP: Profunctor[P]): DinaturalTransformation[Lambda[(A,B) => Tambara[P, A, B]], Lambda[(A,B) => Tambara[Q, A, B]]] = {
  new DinaturalTransformation[Lambda[(A,B) => Tambara[P, A, B]], Lambda[(A,B) => Tambara[Q, A, B]]] {
    def dinat[X, Y](ppp: Tambara[P, X, Y]): Tambara[Q, X, Y] = new Tambara[Q, X, Y] {
      def runTambara[C]: Q[(X, C), (Y, C)] = {
        val p: P[(X,C), (Y,C)] = ppp.runTambara
        f.dinat[(X,C), (Y,C)](ppp.runTambara)
      }
    }
  }
}

Choice Profunctor

Profunctor with additional method left that wrap both types inside Either.

trait ProChoice[P[_, _]] extends Profunctor[P] {
  def left[A,B,C](pab: P[A, B]):  P[Either[A, C], Either[B, C]]
}
  • derived method
def right[A,B,C](pab: P[A, B]): P[Either[C, A], Either[C, B]]
  • Resources

Extranatural Transformation

trait ExtranaturalTransformation[P[_,_],Q[_,_]]{
  def exnat[A,B](p: P[A,B]): Q[A,B]
}

Profunctor Functor

Functor (endofunctor) between two Profunctors.

It is different than regualar Functor: Functor lifts regular function to function working on type constructor: def map[A, B](f: A => B): F[A] => F[B] Profunctor lifts two regular functions to work on type constructor with two holed.

And ProfunctorFunctor lifts dinatural transformation of two Profunctors P[,] => Q[,]

operates on type constructor with one hole (F[A] => F[B]) and ProfunctorFunctor and ProfunctorFunctor map P[A,B] => Q[A,B]

in Scala 2.12 we cannot express type constructor that have hole with shape that is not sepcified)

trait ProfunctorFunctor[T[_]] {
  def promap[P[_,_], Q[_,_]](dt: DinaturalTransformation[P,Q])(implicit PP: Profunctor[P]): DinaturalTransformation[Lambda[(A,B) => T[P[A,B]]], Lambda[(A,B) => T[Q[A,B]]]]
}

Profunctor Monad

trait ProfunctorMonad[T[_]] extends ProfunctorFunctor[T] {
  def proreturn[P[_,_]](implicit P: Profunctor[P]): DinaturalTransformation[P, Lambda[(A,B) => T[P[A,B]]]]
  def projoin[P[_,_]](implicit P: Profunctor[P]): DinaturalTransformation[Lambda[(A,B) => T[T[P[A,B]]]], Lambda[(A,B) => T[P[A,B]]]]
}
  • Laws:
    • promap f . proreturn == proreturn . f
    • projoin . proreturn == id
    • projoin . promap proreturn == id
    • projoin . projoin == projoin . promap projoin

Profunctor Comonad

trait ProfunctorComonad[T[_]] extends ProfunctorFunctor[T] {
  def proextract[P[_,_]](implicit P: Profunctor[P]): DinaturalTransformation[Lambda[(A,B) => T[P[A,B]]], P]
  def produplicate[P[_,_]](implicit P: Profunctor[P]): DinaturalTransformation[Lambda[(A,B) => T[P[A,B]]], Lambda[(A,B) => T[T[P[A,B]]]]]
}
  • Laws
    • proextract . promap f == f . proextract
    • proextract . produplicate == id
    • promap proextract . produplicate == id
    • produplicate . produplicate == promap produplicate . produplicate

Profunctor Yoneda

trait ProfunctorYoneda[P[_,_],A,B] {
  def runYoneda[X,Y](f: X => A, g: B => Y): P[X,Y]
}

is a Profunctor for free, because we can define:

def dimap[AA, BB](l: AA => A, r: B => BB): ProfunctorYoneda[P, AA, BB] = new ProfunctorYoneda[P, AA, BB] {
  def runYoneda[X, Y](l2: X => AA, r2: BB => Y): P[X, Y] = {
    val f1: X => A = l compose l2
    val f2: B => Y = r2 compose r
    self.runYoneda(f1, f2)
  }
}

Profunctor CoYoneda

trait ProfunctorCoyoneda[P[_,_],A,B] {
  type X
  type Y
  def f1: A => X
  def f2: Y => B
  def pxy: P[X,Y]
}

helper constructor:

def apply[XX,YY,P[_,_],A,B](ax: A => XX, yb: YY => B, p: P[XX,YY]): ProfunctorCoyoneda[P,A,B] = new ProfunctorCoyoneda[P,A,B] {
  type X = XX
  type Y = YY
  def f1: A => X = ax
  def f2: Y => B = yb
  def pxy: P[X,Y] = p
}

ProfunctorCoyoneda is a Profunctor for free:

def dimap[C, W](l: C => A, r: B => W): ProfunctorCoyoneda[P, C, W] =
  ProfunctorCoyoneda[X, Y, P, C, W](f1 compose l, r compose f2, pxy)

Procompose

In general Profunctors should have straightforward way to compose them as we have the same category in definition. But to be faithfull with Category Theory definition, Profunctor Composition is defined using exitential types:

trait Procompose[P[_,_],Q[_,_],D,C] {
  type X
  val p: P[X,C]
  val q: Q[D,X]
}

Arrows

Category

Abstraction for operations that can be composed and that provide no-op (id).

trait Compose[F[_, _]] {
  def compose[A, B, C](f: F[B, C], g: F[A, B]): F[A, C] // alias <<<
}

trait Category[F[_, _]] extends Compose[F] {
  def id[A]: F[A, A]
}

Arrow

CommutativeArrow

Arrow Choice

Arrow Apply, Arrow Monad

Arrow Loop

Arrow Zero

Free Arrow

Kleisli

Cokleisli

  • Cats

Adjoint Triples

Dinatural Transformation

Dinatural Transformation is a function that change one Profunctor P into another one Q without modifying the content. It is equivalent to Natural Transformation between two Functors (but for Profunctors).

trait DinaturalTransformation[P[_,_],Q[_,_]]{
  def dinat[A](p: P[A,A]): Q[A,A]
}

Ends & Coends

Ends can be seen as infinite product. End corresponds to forall so polymorphic function:

// P is Profunctor

trait End[P[_,_]] {
  def run[A]: P[A,A]
}

Coend can be seen as infinite coproduct (sum). Coends corresponds to exists

data Coend p = forall x. Coend p x x

Align

These

Data type that represents both sum and product (Non exclusive two values):

Tuple(a,b) => a * b Eiter(a,b) => a + b These(a,b) => (a + b) + a*b

sealed trait These[A,B]
case class This[A, B](a: A) extends These[A,B]
case class That[A,B](b: B) extends These[A,B]
case class Those[A,B](a: A, b: B) extends These[A,B]
  • There is many abstractions that can be implemented for this data type

Resources:

Chronicle Monad

Unfoldable

Resource About Category Theory

About

Patterns from category theory and abstract algebra in Scala


Languages

Language:Scala 100.0%