flatMap功能签名(输入 - >输出)是否建议进行任何展平?

Jas*_*Jas 1 functional-programming coding-style scala code-cleanup

flatMap 签名:

 /* applies a transformation of the monad "content" by composing
  * this monad with an operation resulting in another monad instance 
  * of the same type
  */
  def flatMap(f: A => M[B]): M[B]
Run Code Online (Sandbox Code Playgroud)

无论如何要通过它的签名(输入到输出)(除了名称flat)来理解它的扁平化结构?或者我必须阅读其实现以了解这一点?是不是很好的编码实践意味着我可以通过函数的签名(甚至没有函数名输入输出)来理解它的作用是什么?如果是这样,flatMap这个基本的编程实践如何?还是违反了它?

mat*_*its 6

It helps to understand that the type of the thing that flatMap is defined on is also M and would be something like Traversable[A] or a subclass such as a List[A], or another Monad such as Option or Future. Therefore the left hand side of the function definition that flatMap requires (f: A => M[B]) hints to us that this function processes the individual items contained within the Monad, and produces M[B] for each one. The fact that it then returns M[B] rather than M[M[B]] is a hint that some flattening is taking place.

However I disagree that it should be possible to know exactly what a function does by its signature. For example:

Trait Number {
  def plus(that: Number): Number

  def minus(that: Number): Number
}
Run Code Online (Sandbox Code Playgroud)

如果没有函数名称和可能的文档,我认为期望另一个人可以知道什么plusminus做什么是不合理的.

  • 为了增加你的观点,一个函数的签名不是一切(+1 btw):monad是由他们的**代数**定义的 - 也就是说,一组操作(`flatMap`,`map`,`unit`,等)和操作的*定律*(例如`flatMap`是关联的,并且具有左侧身份和右侧身份).方法签名传达了monad的操作,但不传达其法则. (2认同)