Created
November 13, 2018 19:55
-
-
Save fancellu/a41536698d4808c2a592af828b8cfb99 to your computer and use it in GitHub Desktop.
Simple chaining validation example with pure Scala
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import scala.util.{Failure, Try} | |
val li=List(1,2,3,4) | |
type Transform[F[_],A]=F[A] => F[A] | |
def filterSmall: Transform[Try,Int] ={ ti=> | |
ti.flatMap(i=>if (i>1) Try(i) else new Failure(new Exception(s"$i is too small"))) | |
} | |
def double: Transform[Try,Int] = _.map(_ * 2) | |
def add10: Transform[Try,Int] = _.map(_ + 10) | |
val functions=List(filterSmall, double, add10) | |
def machine(i:Int)=functions.foldLeft(Try(i)){(tryInt,func)=>func(tryInt)} | |
val work=li.map(machine) | |
work.map(_.toString) | |
def add11: Transform[Option,Int] = _.map(_ + 11) | |
def triple: Transform[Option,Int] = _.map(_ * 3) | |
val functions2=List(add11, triple) | |
def machine2(i:Int)=functions2.foldLeft(Option(i)){(optionInt,func)=>func(optionInt)} | |
li.map(machine2) |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
work: List[scala.util.Try[Int]] = List(Failure(java.lang.Exception: 1 is too small), Success(14), Success(16), Success(18)) | |
res1: List[Option[Int]] = List(Some(36), Some(39), Some(42), Some(45)) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment