Advertisement
Guest User

Untitled

a guest
Mar 27th, 2017
36
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.83 KB | None | 0 0
  1. object Simple {
  2. def example(): Unit = {
  3. import scala.collection.mutable.ListBuffer
  4. val pluseOne = (i: Int) => {
  5. i + 1
  6. }
  7. val appender = (result: ListBuffer[Int], item: Int) => {
  8. result += item
  9. }
  10. println(mapping(pluseOne)(appender)(new ListBuffer[Int], 3))
  11. }
  12.  
  13. def mapping[Item, TransformItem, Result](transform: Function1[Item, TransformItem]) =
  14. (reducer: Function2[Result, TransformItem, Result]) => {
  15. (result: Result, item: Item) => {
  16. reducer(result, transform(item))
  17. }
  18. }
  19. }
  20.  
  21.  
  22. object RHT {
  23. def example() {
  24. val strToInt: RHT.Transducer[Int, String] = RHT.mapping { s: String => s.toInt }
  25. def divToTwo: RHT.Transducer[Double, Int] = RHT.mapping { i: Int => i / 2.0 }
  26. def ifNotTwo: RHT.Transducer[Int, Int] = RHT.filtering { i: Int => if (i != 2) false else true }
  27.  
  28. println(List("1", "2", "3").foldLeft[Double](0)((strToInt & divToTwo) >>= (_ + _)))
  29. println(RHT.sequence(strToInt & ifNotTwo & divToTwo, List("1", "2", "3")))
  30. }
  31.  
  32. type ReducingFn[-A, R] = (R, A) => R
  33.  
  34. trait Transducer[+A, -B] {
  35. def apply[R](f: ReducingFn[A, R]): ReducingFn[B, R]
  36.  
  37. def >>=[R] = apply[R] _
  38.  
  39. def compose[C](t2: Transducer[C, A]): Transducer[C, B] = {
  40. val t1 = this
  41. new Transducer[C, B] {
  42. def apply[R](rf: ReducingFn[C, R]) = t1(t2(rf))
  43. }
  44. }
  45.  
  46. def &[C] = compose[C] _
  47. }
  48.  
  49. def mapping[A, B](f: A => B): Transducer[B, A] =
  50. new Transducer[B, A] {
  51. def apply[R](rf: ReducingFn[B, R]) = (r, a) => rf(r, f(a))
  52. }
  53.  
  54. def filtering[A](p: A => Boolean): Transducer[A, A] =
  55. new Transducer[A, A] {
  56. def apply[R](rf: ReducingFn[A, R]) = (r, a) => if (p(a)) r else rf(r, a)
  57. }
  58.  
  59. def sequence[A, B](t: Transducer[B, A], data: Seq[A]) = data.foldLeft(Seq[B]())(t(_ :+ _))
  60. }
  61.  
  62.  
  63. object Application extends App {
  64. Simple.example()
  65. RHT.example()
  66. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement