如何在Scala中实现懒链模式

时间:2019-02-14 05:46:13

标签: scala scala-collections

我正在尝试定义一组“ LazyChains”,以用于将来处理传入的消息。我希望LazyChains的API与Scala集合API(即:Seq,Stream等)没有区别。这将使我能够在消息到达之前提前声明性地定义过滤/转换/动作。这可能是一种众所周知的模式,我不知道其名称,因此这使我很难找到任何结果。

这是我要完成的工作的一个示例:

val chainA = LazyChain()
 .filter(_ > 1)
 .map(x => x * 2)
 .foreach(println _)

val chainB = LazyChain()
 .filter(_ > 5)
 .flatMap(x => Seq(x, x))
 .foreach(println _)

 chainA.apply(2)  // should print "4"
 chainA.apply(1)  // should print nothing
 chainB.apply(10) // should print "10" - twice

Scala集合API中是否已经存在此模式?如果没有,如何实现此类LazyChain

这是我目前的尝试。我似乎无法弄清楚如何使这些类型起作用:

case class LazyChain[I, O](val filter : Option[I => Boolean],
                      val transform : I => O,
                      val action : Option[O => Unit]) {

  def filter(otherFilter : I => Boolean): LazyChain[I, O]  = {
      val newFilter = Some({ x : I => {
        filter.map(_.apply(x)).getOrElse(true) && otherFilter.apply(x)
      }})
      copy(filter = newFilter)
  }

  def map[X](otherTransform : O => X) : LazyChain[I, X] = {
    new LazyChain[I, X](
      filter = filter,
      transform = (x: I) => {
        otherTransform.apply(transform.apply(x))
      },
      /*
        type mismatch;
        [error]  found   : Option[O => Unit]
        [error]  required: Option[X => Unit]
      */
      action = action 
    )
  }

  def flatMap[X](otherTransform : O => Seq[X]) : LazyChain[I, X] = {
    new LazyChain[I, X](
      filter = filter,
      transform = (x: I) => {
        /**
           type mismatch;
             [error]  found   : Seq[X]
             [error]  required: X
        */
        otherTransform.apply(transform.apply(x))
      }
    )
  }

  def foreach(newAction : O => Unit) = {
    copy(action = Some(newAction))
  }

  def apply(element : I) = {
    if (filter.map(_.apply(element)).getOrElse(true)) {
      val postTransform = transform.apply(element)
      action.foreach(_.apply(postTransform))
    }
  }
}
object LazyChain {
  def apply[X]() : LazyChain[X, X] = {
    new LazyChain(filter = None, transform = x => x, action = None)
  }
}

1 个答案:

答案 0 :(得分:2)

您所要做的就是用一些精美的方法包装一个函数I => List[O]。您可以编写implicit class来将这些方法添加到这种类型,但是Kleisli通过各种cats类型类(主要是FilterFunctor)免费完成了其中的大部分工作。

  import cats.implicits._
  import cats.data.Kleisli

  type LazyChain[I, O] = Kleisli[List, I, O]
  def lazyChain[A]: LazyChain[A, A] = Kleisli[List, A, A](a => List(a))

  val chainA = lazyChain[Int]
    .filter(_ > 1)
    .map(x => x * 2)
    .map(println)

  val chainB = lazyChain[Int]
    .filter(_ > 5)
    .flatMapF(x => List(x, x))
    .map(println)

  chainA(2)  // should print "4"
  chainA(1)  // should print nothing
  chainB(10) // should print "10" - twice

它可能看起来太神奇了,所以这是手工制作的版本:

case class LazyChain[A, B](run: A => List[B]) {

  def filter(f: B => Boolean): LazyChain[A, B] = chain(_.filter(f))

  def map[C](f: B => C): LazyChain[A, C] = chain(_.map(f))

  def flatMap[C](f: B => List[C]): LazyChain[A, C] = chain(_.flatMap(f))

  def chain[C](f: List[B] => List[C]): LazyChain[A, C] = LazyChain(run andThen f)
}
object LazyChain {
  def apply[I]: LazyChain[I, I] = new LazyChain(a => List(a))
}

链式转换是一个常见的问题,正如评论所说,使用monix.Observable,iterates等是解决此问题的正确方法(而不是普通的List,流自然是懒惰的。