How to make it a monad?

和自甴很熟 提交于 2019-12-11 05:39:29

问题


I am trying to validate a list of strings sequentially and define the validation result type like that:

import cats._, cats.data._, cats.implicits._

case class ValidationError(msg: String)
type ValidationResult[A] =  Either[NonEmptyList[ValidationError], A]
type ListValidationResult[A] = ValidationResult[List[A]] // not a monad :(

I would like to make ListValidationResult a monad. Should I implement flatMap and pure manually or there is an easier way ?


回答1:


I suggest you to take a totally different approach leveraging cats Validated:

import cats.data.Validated.{ invalidNel, valid }

val stringList: List[String] = ???

def evaluateString(s: String): ValidatedNel[ValidationError, String] =
  if (???) valid(s) else invalidNel(ValidationError(s"invalid $s"))

val validationResult: ListValidationResult[String] = 
  stringList.map(evaluateString).sequenceU.toEither

It can be adapted for a generic type T, as per your example.


Notes:

  • val stringList: List[String] = ??? is the list of strings you want to validate;
  • ValidatedNel[A,B] is just a type alias for Validated[NonEmptyList[A],B];
  • evaluateString should be your evaluation function, it is currently just an unimplemented stub if;
  • sequenceU you may want to read cats documentation about it: sequenceU;
  • toEither does exactly what you think it does, it converts a Validated[A,B] to an Either[A,B].

As @Michael pointed out, you could also use traverseU instead of map and sequenceU

val validationResult: ListValidationResult[String] = 
  stringList.traverseU(evaluateString).toEither


来源:https://stackoverflow.com/questions/43211940/how-to-make-it-a-monad

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!