4

简单的问题,我已经看过这个问题了:在 Scalaz7 中管理导入,但我不知道如何将rightandleft方法最小地注入到我的对象中以构造\/.

我确实尝试过:

import syntax.ToDataOpsTo...以及http://eed3si9n.com/learning-scalaz-day13syntax.ToIdOps中建议的其他变体。

简单的例子:

import scalaz.{\/, syntax}
import // What goes here

class Test {

    def returnEitherT(h: Int): String \/ Int = {
        h right
    }
}

谢谢,杰森。

===========

我通过使用解决了它,import syntax.id._但我不确定为什么会这样。

4

2 回答 2

4

syntax.id contains syntax for "plain" values, i.e. it places no constraints on the type of the value.

In general, when you import syntax for an expression of the form x.op, the place to import the syntax depends on the type of x, because op needs to be a valid operation on that type.

Because \/[A, B] is universally quantified for A and B, using the syntax x.left and x.right places no constraints on the type of x. Hence, it belongs in syntax.id.

For a working understanding of what syntax is available where, it is worth looking at the source of some of the modules that make up the syntax packages. For example, contrast IdOps[A], which has syntax for any A, with FunctorOps[F[_],A], which has the requirement that F is a Functor.


I am not sure where the name id comes from exactly; perhaps it is related to the identity functor Id, which can be defined as type Id[A] = A. If you had to choose a type constraint for values usable with syntax.id, it would be that they are in Id. Being universally quantified in A, the operations can't know about the structure of a value of A, hence they can't be structure-altering operations on A.

于 2013-04-25T11:09:11.710 回答
2

自 scalaz 7 以来,正确的导入是:

import scalaz.syntax.either._
于 2015-06-17T08:47:21.213 回答