[英]Scala with Cats - Cartesian + Validated
我正在用《 Advanced scala with cats
》一书中的Advanced scala with cats
做简单的练习。
我想将Cartesian
与Validated
一起使用。
/*
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( ^
没有看到你的进口我猜问题是,你错过了Semigroup
例如List
(或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._
开始。
这里的问题是,当您将两个实例与product
结合使用时, Validated
累积失败,并且在特定上下文中“累积”的含义由Semigroup
实例确定,该无效类型告诉您如何将两个无效值一起添加。
对于List
(或Vector
),串联对于此累加操作有意义,并且Cats为任何List[A]
提供串联Semigroup
,但是为了在此处应用它,您必须显式导入(从cats.implicits
或来自cats.instances.list
)。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.