Guest User

Untitled

a guest
Nov 13th, 2018
103
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 0.71 KB | None | 0 0
  1. import scala.util.{Failure, Try}
  2.  
  3. val li=List(1,2,3,4)
  4.  
  5. type Transform[F[_],A]=F[A] => F[A]
  6.  
  7. def filterSmall: Transform[Try,Int] ={ ti=>
  8. ti.flatMap(i=>if (i>1) Try(i) else new Failure(new Exception(s"$i is too small")))
  9. }
  10.  
  11. def double: Transform[Try,Int] = _.map(_ * 2)
  12.  
  13. def add10: Transform[Try,Int] = _.map(_ + 10)
  14.  
  15. val functions=List(filterSmall, double, add10)
  16.  
  17. def machine(i:Int)=functions.foldLeft(Try(i)){(tryInt,func)=>func(tryInt)}
  18.  
  19. val work=li.map(machine)
  20.  
  21. work.map(_.toString)
  22.  
  23. def add11: Transform[Option,Int] = _.map(_ + 11)
  24.  
  25. def triple: Transform[Option,Int] = _.map(_ * 3)
  26.  
  27. val functions2=List(add11, triple)
  28.  
  29. def machine2(i:Int)=functions2.foldLeft(Option(i)){(optionInt,func)=>func(optionInt)}
  30.  
  31. li.map(machine2)
Add Comment
Please, Sign In to add comment