【问题标题】:Scala with Cats - Cartesian + ValidatedScala 与 Cats - 笛卡尔 + 验证
【发布时间】:2017-02-08 01:46:06
【问题描述】:

我正在自己做一个来自Advanced scala with cats 的简单练习。

我想将CartesianValidated 一起使用。

/*
this works
*/
type ValidatedString =  Validated[ Vector[String], String]
Cartesian[ValidatedString].product(
  "a".valid[Vector[String]],
  "b".valid[Vector[String]]
)

/* this doesnt work*/
type Result[A] = Validated[List[String], A]
Cartesian[ValidatedString].product(
    f(somevariable)//returns Result[String],
    g(somevariable)//returns Result[Int],
).map(User.tupled) // creates an user from the returned string, int

我完全一无所知。有什么提示吗? 我得到:

could not find implicit value for parameter instance: cats.Cartesian[Result] Cartesian[Result].product( ^

【问题讨论】:

  • 在第一个示例中,您根据Vector[] 定义ValidatedString,而在第二个示例中,您根据List[] 定义它。这是真正的区别吗?
  • 这是一个小问题,但你的第一个代码 sn-p 实际上工作,因为 ValidatedString 不是类型构造函数。这将使这个问题对未来的读者更有用,以确保您的代码描述正确。

标签: scala scala-cats


【解决方案1】:

如果没有看到您的导入,我猜问题是您缺少ListSemigroup 实例(或Vector - 不清楚您要使用哪个),因为以下内容对我有用:

import cats.Cartesian, cats.data.Validated, cats.implicits._

type Result[A] = Validated[List[String], A]

Cartesian[Result].product(
  "a".valid[List[String]],
  "a".valid[List[String]]
)

您可以将cats.implicits._ 部分替换为以下内容:

import cats.instances.list._
import cats.syntax.validated._

…但我建议以cats.implicits._ 开头。

这里的问题是Validated 在将两个实例与product 组合时会累积失败,而“累积”在特定上下文中的含义由Semigroup 无效类型的实例决定,该实例告诉您如何将两个无效值“添加”在一起。

List(或Vector)的情况下,串联对于这个累加操作是有意义的,并且Cats为任何List[A]提供了串联Semigroup,但是为了让它在这里应用你必须显式导入它(从cats.implicitscats.instances.list)。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2017-06-02
    • 1970-01-01
    • 1970-01-01
    • 2016-11-22
    • 2013-01-15
    • 2019-06-04
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多