scalascalazkleisli

Are there interesting examples of composing Kleisli endomorphisms?


This is a follow-up to my previous question

We can define a function that finds an XML node by path (List[String], XmlNode) => Option[XmlNode] as a composition of functions (String, XmlNode) => Option[XmlNode] that get a child node by name.

We use the fact that functions A => M[A], where M is a monad, form a monoid and so we can easily compose them.

Now I wonder whether there are other interesting examples of composing such functions.


Solution

  • knight’s quest example from learning Scalaz

    http://eed3si9n.com/learning-scalaz/A-knights-quest.html

    before

    def in3: List[KnightPos] =
      for {
        first <- move
        second <- first.move
        third <- second.move
      } yield third
    
    def canReachIn3(end: KnightPos): Boolean = in3 contains end
    

    after(use scalaz.Endomorphic)

    val moveK: Kleisli[List, KnightPos, KnightPos] = Kleisli(_.move)
    
    def in(n: Int): List[KnightPos] =
      moveK.endo.multiply(n).run.run(this)
    
    def canReachIn(n: Int, end: KnightPos): Boolean = in(n) contains end
    

    https://gist.github.com/xuwei-k/c77aa4e19c0b4d4c10e2/revisions