问题描述
这是我之前的问题的后续操作.
假设我需要编写一个函数validate
,以确保给定的字符串列表由"a","b"和一个或多个"c"组成.
This is a follow up to my previous question.
Suppose I need to write a function validate
in order to make sure that a given list of strings consists of "a", "b", and one or more "c".
def validate(ss: List[String]): Either[NonEmptyList[MyError], Unit] = ???
假设我有三个函数来检查给定的字符串是"a","b"还是"c":
Suppose I have three functions to check if a given string is "a", "b", or "c":
def validateA(str: String): Either[MyError, Unit] = ???
def validateB(str: String): Either[MyError, Unit] = ???
def validateC(str: String): Either[MyError, Unit] = ???
如何编写这些函数以实现validate
?
How to compose those functions to implement validate
?
一种解决方案是解析器组合器"方法.为类型Validator = Either[NonEmptyList[MyError], List[String]]
定义一个monad实例,类似于解析器组合器等类似oneOrMore
的组合器.
One solution is a "parser combinators" approach. Define a monad instance for type Validator = Either[NonEmptyList[MyError], List[String]]
, combinators like oneOrMore
similar to parser combinators etc.
我想知道是否有更简单的解决方案.
I am wondering whether there is an easier solution.
推荐答案
我建议您利用cats
Validated
.
如果您确实不想更改您的validateT
方法签名,请定义一些辅助方法:
Let's define some helper methods, if you really don't want to change your validateT
methods signatures:
def validateA_(str: String): ValidatedNel[MyError, Unit] = validateA(str).toValidatedNel
def validateB_(str: String): ValidatedNel[MyError, Unit] = validateB(str).toValidatedNel
def validateC_(str: String): ValidatedNel[MyError, Unit] = validateC(str).toValidatedNel
然后,您可以实现validate_
辅助函数:
Then you can implement a validate_
helper function:
import cats.data.Validated.{ invalidNel, valid }
def validate_(ss: List[String]): ValidatedNel[MyError, Unit] = ss match {
case a :: b :: c if c.nonEmpty =>
validateA_(a) combine validateB_(b) combine c.traverseU_(validateC_)
case _ => invalidNel(MyError(???)) //List too short
}
最后将您的validate
函数实现为:
And finally implement your validate
function as:
def validate(ss: List[String]): Either[NonEmptyList[MyError], Unit] =
validate_(ss).toEither
假设:对输入列表进行了排序,如果输入列表短于3
元素,则可以接受特定错误(例如,列表太短).
Assumptions: the input list is sorted and if it is shorter than 3
elements a specific error (e.g. list too short) is acceptable.
这篇关于验证字符串列表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!