Skip to content

Latest commit

 

History

History
64 lines (44 loc) · 2.13 KB

monad.md

File metadata and controls

64 lines (44 loc) · 2.13 KB

##Monads in scala.

Monads are formally defined in a branch of mathematics called Category Theory and correspond to a useful functional design pattern in scala. This article aims to describe the formal definition and the relationship to scala.

We firstly define Category, Functor, Natural Transformation and Monad.

a Category C is

  • a set of objects
  • a set of morphisms which are relations between objects
  • a composition operator * for morphisms

The constraints on a category are:

  • every object has an identity morphism
  • the composition operator is associative

A Functor from Category A to Category B (A→B)

  • relates objects in A to objects in B
  • relates morphisms in A to morphisms in B

A Functor also

  • preserves identity morphisms
  • preserves composition of morphisms

Note that for category A there is an obvious identity functor 1A:A→A

A Natural Transformation μ

  • relates two functors F,G:A→B
  • relates each object a in A to a morphism μ(a): F(a)→G(a) in category B such that for every morphism f:a→a' in A we have μ(a') * F(f) = G(f) * μ(a) (commutativity).

a Monad has

  • a functor F from Category A to Category A (endomorphic functor)
  • a natural transformation ν:1A→F
  • a natural transformation μ:FxF→F
  • μ is associative with F (μ * Fμ = μ * μF)
  • ν is the effective inverse of μ (μ * Fν = μ * νF = 1F)

###Examples in Scala ####Category objects = Scala Types (Int,String,List[String],..), morphisms = functions between types

####Functor ToList: Types->Types given by ToList(t)=List[t] for t in Types, maps morphisms obviously

####Monad:

  • functor=ToList,
  • ν(t)=List[t], inserts value into a singleton list
  • μ(t,t)=+, concatenation of two lists
trait Monad[M[_]] {
 def flatMap[A, B](x: M[A], f: A => M[B]): M[B]
 def point[A](x: A): M[A]
 def map[A, B](x: M[A], f: A => B): M[B] = flatMap(x, a => point(f(a)))
}

Now give me one property or theorem of monads in general and its application to the Category of types and functions in Scala.