簡體   English   中英

在 Scala 中使用來自 Cats 庫的驗證

[英]Using Validated from the Cats library in Scala

無法理解Semigroupal.productSemigroupal.tuple2之間的實際區別。 這是一個簡短的例子:

import cats.Semigroupal
import cats.data.Validated
import cats.data.Validated.Invalid
import cats.instances.list._ // for Monoid

  type AllErrorsOr[A] = Validated[List[String], A]
  def bothInvalid = {
    Semigroupal[AllErrorsOr].product(
      Validated.invalid(List("Error 1")),
      Validated.invalid(List("Error 2"))
    )
  }

  def bothInvalidTuple = {
    Semigroupal.tuple2(
      Validated.invalid(List("Error 1")),
      Validated.invalid(List("Error 2"))
    )
  }

  def bothValid = {
    Semigroupal[AllErrorsOr].product(
      Validated.valid(10),
      Validated.valid(20)
    )
  }

  def bothValidTuple = {
    Semigroupal.tuple2(
      Validated.valid(10),
      Validated.valid(20)
    )
  }

對於無效, bothInvalidbothInvalidTuple給出相同的結果。 對於有效值,僅編譯第一個。 我得到的錯誤:

錯誤:(40, 23) 找不到參數 semigroupal 的隱式值:cats.Semigroupal[[+A]cats.data.Validated[Nothing,A]] Semigroupal.tuple2(

似乎(如果我沒記錯的話)Scala 試圖找到Monoid來組合Nothing ,而不是List[String] 如何讓它與tuple2工作?

只是一些泛型沒有被推斷出來。 嘗試明確指定它們

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

  def bothInvalid: AllErrorsOr[(Int, Int)] = {
    Semigroupal[AllErrorsOr].product[Int, Int](
      Validated.invalid(List("Error 1")),
      Validated.invalid(List("Error 2"))
    )
  }

  def bothInvalidTuple: AllErrorsOr[(Int, Int)] = {
    Semigroupal.tuple2[AllErrorsOr, Int, Int](
      Validated.invalid(List("Error 1")),
      Validated.invalid(List("Error 2"))
    )
  }

  def bothValid: AllErrorsOr[(Int, Int)] = {
    Semigroupal[AllErrorsOr].product[Int, Int](
      Validated.valid(10),
      Validated.valid(20)
    )
  }

  def bothValidTuple: AllErrorsOr[(Int, Int)] = {
    Semigroupal.tuple2[AllErrorsOr, Int, Int](
      Validated.valid(10),
      Validated.valid(20)
    )
  }

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM