Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- object Simple {
- def example(): Unit = {
- import scala.collection.mutable.ListBuffer
- val pluseOne = (i: Int) => {
- i + 1
- }
- val appender = (result: ListBuffer[Int], item: Int) => {
- result += item
- }
- println(mapping(pluseOne)(appender)(new ListBuffer[Int], 3))
- }
- def mapping[Item, TransformItem, Result](transform: Function1[Item, TransformItem]) =
- (reducer: Function2[Result, TransformItem, Result]) => {
- (result: Result, item: Item) => {
- reducer(result, transform(item))
- }
- }
- }
- object RHT {
- def example() {
- val strToInt: RHT.Transducer[Int, String] = RHT.mapping { s: String => s.toInt }
- def divToTwo: RHT.Transducer[Double, Int] = RHT.mapping { i: Int => i / 2.0 }
- def ifNotTwo: RHT.Transducer[Int, Int] = RHT.filtering { i: Int => if (i != 2) false else true }
- println(List("1", "2", "3").foldLeft[Double](0)((strToInt & divToTwo) >>= (_ + _)))
- println(RHT.sequence(strToInt & ifNotTwo & divToTwo, List("1", "2", "3")))
- }
- type ReducingFn[-A, R] = (R, A) => R
- trait Transducer[+A, -B] {
- def apply[R](f: ReducingFn[A, R]): ReducingFn[B, R]
- def >>=[R] = apply[R] _
- def compose[C](t2: Transducer[C, A]): Transducer[C, B] = {
- val t1 = this
- new Transducer[C, B] {
- def apply[R](rf: ReducingFn[C, R]) = t1(t2(rf))
- }
- }
- def &[C] = compose[C] _
- }
- def mapping[A, B](f: A => B): Transducer[B, A] =
- new Transducer[B, A] {
- def apply[R](rf: ReducingFn[B, R]) = (r, a) => rf(r, f(a))
- }
- def filtering[A](p: A => Boolean): Transducer[A, A] =
- new Transducer[A, A] {
- def apply[R](rf: ReducingFn[A, R]) = (r, a) => if (p(a)) r else rf(r, a)
- }
- def sequence[A, B](t: Transducer[B, A], data: Seq[A]) = data.foldLeft(Seq[B]())(t(_ :+ _))
- }
- object Application extends App {
- Simple.example()
- RHT.example()
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement