2016-09-29 88 views
2

我正在從我自己的書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( ^

+0

在你的第一個例子中,你可以用'Vector []'定義'ValidatedString',而在第二個例子中,你可以用'List []'來定義它。這是真正的區別嗎? –

+0

這是一個小問題,但是您的第一個代碼片段_doesn't_實際上並不工作,因爲'ValidatedString'不是一個類型構造函數。這將使這個問題對未來的讀者更有用,以確保您的代碼被正確描述。 –

回答

4

沒有看到你的進口我猜的問題是您遺漏了List一個Semigroup實例(或Vector要使用 - 它並不清楚),因爲以下爲我工作:

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

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._部分

...但我建議從cats.implicits._開始。

這裏的問題是,Validated累積失敗當你把兩個實例與product,以及什麼是「積累」,在特定情況下是指由Semigroup實例爲無效的類型,它告訴你如何「添加」兩無效的決定值一起。

List(或Vector)的情況下,串聯是有道理的,這種積累操作和貓提供串聯Semigroup任何List[A],但爲了得到它的應用在這裏你必須明確地導入(無論是從cats.implicits或從cats.instances.list)。

+0

我缺少'import cats.implicits._' 謝謝! –