繁体   English   中英

Scala与猫-笛卡尔+验证

[英]Scala with Cats - Cartesian + Validated

我正在用《 Advanced scala with cats 》一书中的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( ^

没有看到你的进口我猜问题是,你错过了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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM