Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to understand monad in scala

I just understood what type constructor and higher kinded types states for and now I'm trying to understand Monad. Here is how Monad trait looks in scalaz:

trait Monad[F[_]] extends Applicative[F] with Bind[F] { self =>
  ////

  override def map[A,B](fa: F[A])(f: A => B) = bind(fa)(a => point(f(a)))
  //The rest is omitted

}

The question is I don't kind of understand why Monad is a higher kinded type? We have standard List[T], Option[T] monads which are not higher kinded types.

I'm not a Theory Category expert so I treat monad as a container with monads laws.

Why don't we just declare a monad as follows:

trait Monad[V]{
    //...
}

Not a higher kind.

How would standard Option[T] monad look like in that case as a a subclass for instance?

like image 931
St.Antario Avatar asked Sep 28 '17 09:09

St.Antario


1 Answers

I don't kind of understand why Monad is a higher kinded type?

I think the fastest way to see why it has to be a higher kinded type is to try and create a signature for pure where the type parameter isn't itself a type constructor:

// Doesn't compile
trait Monad[V]{
  def pure[A](a: A): V[A]
}

Of course, that doesn't work because we can't write V[A] for an arbitrary type parameter, it has to be a type constructor, particularly one of kind * -> *

How would standard Option[T] monad look like in that case as a subclass for instance

Another thing about a Monad (and a Functor for that matter) being a type constructor is that we create a single representation of Monad[List], for example, and get it for free for all T arguments of that List because of polymorphic types and theorms for free. Again, you could not by the virtue of the signature of Monad implement it without a type constructor.

We have standard List[T], Option[T] monads which are not higher kinded types.

That's right. They are not higher kinded because T itself isn't required to be a type constructor for any operations of List[T] or Option[T] to work, but T in that sense can represent any type. This means that although Option[T] is of kind * -> *, I can still construct it with a List to produce a Option[List[T]].

like image 144
Yuval Itzchakov Avatar answered Sep 19 '22 13:09

Yuval Itzchakov