如何在Scala中编写聚合模式?

时间:2011-09-12 19:23:00

标签: design-patterns scala aggregate-functions

假设我有Iterator[A]大小无限),我想从中获取Iterator[B],其中聚合了A类的后续某些值。

实施例: 我有字符串列表:

Iterator(
    "START",
    "DATA1",
    "DATA2",
    "DATA3",
    "START",
    "DATA1",
    "DATA2",
    //.. 10^10 more records
)

我想加入从START到NEXT START的字符串。即写解析器。

Iterator(
"START DATA1 DATA2 DATA3",
"START DATA1 DATA2",
    //.. 10^10 / 5 more records
)

我知道如何强制执行此操作,但我希望使用scala高阶函数来完成它。有什么想法吗?

PS EIP汇总http://camel.apache.org/aggregator2.html

4 个答案:

答案 0 :(得分:5)

嗯,无限的流会相当戏剧性地改变事物。假设我理解你的其他情况,这应该有效:

def aggregate(it: Iterator[String]) = new Iterator[String] {
  if (it.hasNext) it.next
  def hasNext = it.hasNext
  def next = "START " + (it.takeWhile(_ != "START")).mkString(" ")
}

这样你就可以:

val i = aggregate(yourStream.iterator)
i.take(20).foreach(println) // or whatever

答案 1 :(得分:5)

如果您需要功能性解决方案,则应使用Streams而不是迭代器(流是不可变的)。这是一种可能的方法:

def aggregate(strs: Stream[String] ) = { 
  aggregateRec( strs )
}

def aggregateRec( strs: Stream[String] ): Stream[String] = {
  val tail = strs.drop(1)
  if( tail.nonEmpty ) {
    val (str, rest ) = accumulate( tail )
    Stream.cons( str, aggregateRec( rest ) )
  }
  else Stream.empty
}

def accumulate( strs: Stream[String] ): (String, Stream[String])  = {
  val first = "START " + strs.takeWhile( _ != "START").mkString(" ")
  val rest = strs.dropWhile( _ != "START" )
  ( first, rest )
}

按预期工作:

val strs = Stream( "START", "1", "2", "3", "START", "A", "B" )
val strs2 = aggregate( strs )
strs2 foreach println

答案 2 :(得分:1)

您可以尝试折叠:

val ls = List(
  "START",
  "DATA1",
  "DATA2",
  "DATA3",
  "START",
  "DATA1",
  "DATA2"
)

(List[List[String]]() /: ls) { (acc, elem) =>
  if (elem == "START")
    List(elem) :: acc // new head list
  else
    (elem :: acc.head) :: acc.tail // prepend to current head list
} map (_.reverse mkString " ") reverse;

答案 3 :(得分:0)

使用Streams:

object Iter {
  def main(args: Array[String]) {
    val es = List("START", "DATA1", "DATA2", "START", "DATA1", "START")
    val bit = batched(es.iterator, "START")
    println(bit.head.toList)
    println(bit.tail.head.toList)
  }

  def batched[T](it: Iterator[T], start: T) = { 
    def nextBatch(): Stream[List[T]] = { 
      (it takeWhile { _ != start }).toList match {
        case Nil => nextBatch()
        case es => Stream.cons(start :: es, nextBatch())
      }
    }
    nextBatch()
  }

}