Is a collection with flatMap a monad?

后端 未结 5 686
独厮守ぢ
独厮守ぢ 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:58

    I think a collection with a flatMap is not necessarily a monad. It does not necessarily fit the monad laws. These laws are probably better explained in Functional Programming in Scala than I could do.

    Recently I heard from a coworker a simplified and pragmatic explanation (with self-consciousness) of what is a monad in Scala: something you can put in a for comprehension.

    I'm not a monad expert, but it seems to me that this is not true, and so it is for collections with flatMap. The most obvious exemple of this is in Scala lib Either as it is not right biaised and it does not have any flatMap method until you project it to a side (and this projection is not monadic as it returns Either). As far as I understand it, a type is not a monad (or a monoid or whatever), but a type may have a monad (or even many ones? not sure but would be interested by any exemple (but maybe Either is the good one?)).

    I think Scala is a pragmatic language, in which it can sometimes be useful to forget about strict rules and help programmers to do their job more easily. Not all programmers care about what is a monad, but many probably want to flatten a List[Set[Int]] at some point and flatMap may help them.

    This reminds me of this blog post in which the Future type is considered as copointed for tests.

提交回复
热议问题