Is a collection with flatMap a monad?

后端 未结 5 674
独厮守ぢ
独厮守ぢ 2021-02-07 15:30

Scala has the trait Iterable[A] that defines

def flatMap[B](f: (A) ⇒ GenTraversableOnce[B]): Iterable[B] 

That certainly looks

5条回答
  •  隐瞒了意图╮
    2021-02-07 15:35

    To answer your question in the context of core Scala excluding Scalaz and category theory, while core Scala does not have a trait, class or object named "Monad", it does implement an object-oriented concept of monad that I will reference as Orderskian monad, since it was invented and implemented primarily by Martin Ordersky (and Adrian Moors according to http://igstan.ro/posts/2012-08-23-scala-s-flatmap-is-not-haskell-s.html).

    An Orderskian monad requires at least map, flatmap and withFilter functions as explained in "Programming In Scala" (2Ed:PDF edition:chapter 23:page 531) by Martin Odersky where he states "Therefore, map, flatMap and withFilter can be seen as an object-oriented version of the functional concept of monad." Based on this, Scala Collections are Orderskian monads.

    To answer your question including Scalaz, it requires a scalaz.Monad implementatation to extend the Monad trait and implement two abstract functions, pure and bind, in order to satisfy three laws requiring them (http://scalaz.github.io/scalaz/scalaz-2.9.1-6.0.2/doc/index.html#scalaz.Monad). Core Scala collections do not meet those requirements so nothing could ever break their scalaz.Monad-ness because it never existed. To the extent that scalaz.Monad models category theory monad, this argument applies to the latter.

提交回复
热议问题