相关疑难解决方法(0)

Scala中的方法参数验证,用于理解和monad

我正在尝试验证无效方法的参数,但我找不到解决方案......

谁能告诉我该怎么办?

我正在尝试这样的事情:

  def buildNormalCategory(user: User, parent: Category, name: String, description: String): Either[Error,Category] = {
    val errors: Option[String] = for {
      _ <- Option(user).toRight("User is mandatory for a normal category").right
      _ <- Option(parent).toRight("Parent category is mandatory for a normal category").right
      _ <- Option(name).toRight("Name is mandatory for a normal category").right
      errors : Option[String] <- Option(description).toRight("Description is mandatory for a normal category").left.toOption
    } yield errors
    errors match {
      case Some(errorString) => Left( Error(Error.FORBIDDEN,errorString) )
      case None =>  Right( buildTrashCategory(user) )
    }
  }
Run Code Online (Sandbox Code Playgroud)

monads scala either for-comprehension

33
推荐指数
3
解决办法
7950
查看次数

为什么`scala.util.Try`在"Scala中的函数式编程"一书中的"无异常处理错误"一章中没有提到?

在"Scala中的函数式编程"一书的"无异常处理错误"一章中,作者给出了:

  1. 从函数体中抛出异常的问题
  2. 使用Option,如果我们不关心实际的异常
  3. 使用Either如果我们关心实际的异常

scala.util.Try没有提到.从我的角度来看,我认为Try当我们关心实际的异常时,它是非常合适的,为什么没有提到呢?我错过了什么理由?

scala exception either

21
推荐指数
1
解决办法
1752
查看次数

验证与分离

假设我想编写一个带有以下签名的方法:

def parse(input: List[(String, String)]):
  ValidationNel[Throwable, List[(Int, Int)]]
Run Code Online (Sandbox Code Playgroud)

对于输入中的每对字符串,它需要验证两个成员都可以解析为整数,并且第一个成员小于第二个.然后它需要返回整数,累积任何出现的错误.

首先,我将定义一个错误类型:

import scalaz._, Scalaz._

case class InvalidSizes(x: Int, y: Int) extends Exception(
  s"Error: $x is not smaller than $y!"
)
Run Code Online (Sandbox Code Playgroud)

现在我可以按如下方式实现我的方法:

def checkParses(p: (String, String)):
  ValidationNel[NumberFormatException, (Int, Int)] =
  p.bitraverse[
    ({ type L[x] = ValidationNel[NumberFormatException, x] })#L, Int, Int
  ](
    _.parseInt.toValidationNel,
    _.parseInt.toValidationNel
  )

def checkValues(p: (Int, Int)): Validation[InvalidSizes, (Int, Int)] =
  if (p._1 >= p._2) InvalidSizes(p._1, p._2).failure else p.success

def parse(input: List[(String, String)]):
  ValidationNel[Throwable, List[(Int, Int)]] = input.traverseU(p =>
    checkParses(p).fold(_.failure, checkValues …
Run Code Online (Sandbox Code Playgroud)

validation functional-programming scala either scalaz

19
推荐指数
1
解决办法
2655
查看次数