使用免费Monad与其中任何一个

时间:2017-08-31 11:08:42

标签: scala functional-programming scala-cats either free-monad

我有两个DSL - EmployeeActionContactAction。这是我的特质(行动)

完成要点:link

sealed trait EmployeeAction[R]
case class GetEmployee(id: Long) extends EmployeeAction[Either[Error, Employee]]

sealed trait ContactAction[R]
case class GetAddress(empId: Long) extends ContactAction[Either[Error, Address]]

我已经使用了cats' CoproductInject这是我获取经理地址的计划:

type Program = Coproduct[EmployeeAction, ContactAction, A]

def findManagerAddress(employeeId: Long)
               (implicit EA: EmployeeActions[Program],
                CA: ContactActions[Program]): Free[Program, Address] = {
  import EA._, CA._
  for {
    employee <- getEmployee(employeeId)
    managerAddress <- getAddress(employee.managerId)
  } yield managerAddress
}

以上不会编译,因为getEmployee会返回Either[Error, Employee]。我如何在Free中理解这一点?

我尝试使用EitherT monad变换器进行包装,如下所示,它在IntelliJ中没有显示错误,但在构建时失败。

for {
  employee <- EitherT(getEmployee(employeeId))
  managerAddress <- EitherT(getAddress(employee.managerId))
} yield managerAddress

以下是错误:

[scalac-2.11] /local/home/arjun/code/Free/src/FreeScalaScripts/src/free/program/Program.scala:71: error: no type parameters for method apply: (value: F[Either[A,B]])cats.data.EitherT[F,A,B] in object EitherT exist so that it can be applied to arguments (cats.free.Free[free.Program,Either[free.Error,free.Employee]])
[scalac-2.11]  --- because ---
[scalac-2.11] argument expression's type is not compatible with formal parameter type;
[scalac-2.11]  found   : cats.free.Free[free.Program,Either[free.Error,free.Employee]]
[scalac-2.11]  required: ?F[Either[?A,?B]]
[scalac-2.11]       employee <- EitherT(getEmployee(employeeId))
[scalac-2.11]                   ^

如何理解以及如何将错误传播给调用者?我想知道呼叫失败的所有员工ID。

1 个答案:

答案 0 :(得分:0)

F[Either[A, B]]需要Free[Program, Either[Error, Employee]],但您有Free[Program, A],这是不兼容的。

type MyAlias[A] = Free[Program, A] 创建类型别名的解决方案:

getEmployee

然后让MyAlias[Either[Error, Employee]]返回getAddress,同时{{1}}。