【问题标题】:Using Free Monad with Either将 Free Monad 与 Either 一起使用
【发布时间】:2018-02-09 07:49:16
【问题描述】:

我有两个 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]                   ^

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

【问题讨论】:

  • EitherT 的编译错误是什么?
  • @ZiyangLiu 我已经更新了问题中的错误

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


【解决方案1】:

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

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

type MyAlias[A] = Free[Program, A]

然后让getEmployee 返回MyAlias[Either[Error, Employee]]getAddress

【讨论】:

  • 实际上,here is the gist 我所拥有的。即使使用 Type Alias,for 理解也不起作用,因为 EitherT 和 Free 无法组合。我想知道如何处理。
猜你喜欢
  • 2021-09-04
  • 2020-11-16
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-08-22
  • 1970-01-01
  • 2018-10-01
相关资源
最近更新 更多