Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- 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)
Add Comment
Please, Sign In to add comment