Validation Check and Monad List

I am trying to come up with something similar to the following:

val s: Validation[String, Int] = 1.success def s2(i: Int): Validation[String, Int] = i.success val result = for { i <- s j <- List(1, 2) k <- s2(j) } yield "fine"; 

The above code does not compile, and I understand syntactically it does not make sense.

I am trying to execute a checklist in a monadic way. How do I achieve this?

+6
source share
2 answers

If you have checklist A , you can include it in checklist A with sequence :

 List(1, 2).map(s2).sequence[({type l[a]=Validation[String, a]})#l, Int] 

(if I understood the question correctly). So you get

 val result = for { i <- s k <- List(1, 2).map(s2).sequence[({type l[a]=Validation[String, a]})#l, Int] } yield "fine" 
+8
source

You seem to be using validation for a side effect. This is not what it is for. You use return values ​​in functional programming.

Validation for understanding continues with success, but is interrupted by an error and returns a failure.

 scala> def g(i: Int): Validation[String, Int] = { println(i); if(i % 2 == 0) i.success else "odd".fail } g: (i: Int)scalaz.Validation[String,Int] scala> val result = for { | i <- g(1) | j <- g(2) | } yield (i,j) 1 result: scalaz.Validation[String,(Int, Int)] = Failure(odd) scala> val result = for { | i <- g(2) | j <- g(1) | } yield (i,j) 2 1 result: scalaz.Validation[String,(Int, Int)] = Failure(odd) scala> val result = for { | i <- g(2) | j <- g(2) | } yield (i,j) 2 2 result: scalaz.Validation[String,(Int, Int)] = Success((2,2)) scala> val result = for { | i <- g(1) | j <- g(1) | } yield (i,j) 1 result: scalaz.Validation[String,(Int, Int)] = Failure(odd) 
+4
source

Source: https://habr.com/ru/post/894714/


All Articles