简体   繁体   中英

How to map on a inner Functor (ValidationNel[A, Option[B]])

I need a combinator to convert a ValidationNel[A, Option[B]] into a ValidationNel[A, Option[C]] to map (by map the option) on the success of the validation.

Here is the code :

  def mapmap[A, B, C](valid: ValidationNel[A, Option[B]], f: B => C) : ValidationNel[A, Option[C]] =
    valid.map(_.map(f))

I've also tried to compose functor (but unfortunately, that do not compile) :

def nestedMap[A, B, C](valid: ValidationNel[A, Option[B]])(f: B => C) : ValidationNel[A, Option[C]] = {
  val composed = Functor[Validation].compose[Option]
  composed.map(valid, f)
}

Is there a better way ?

We need a type lambda to retrieve the Functor instance for Validation .

Here is the code :

def nestedMap[A, B, C](valid: ValidationNel[A, Option[B]])(f: B => C) : ValidationNel[A, Option[C]] = {
  val composed = Functor[({type l[a] = ValidationNel[A, a]})#l].compose[Option]
  composed.map(valid)(f)
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM