1

有没有一种惯用的方式来分块和连接?

我发现的方式(字节示例):

    1.
import scodec.bits.ByteVector    

def byteChunk(n: Int): Process1[ByteVector, ByteVector] =
    process1.chunk(n).map(_.reduce(_ ++ _))

但在这种情况下,并不真正需要中间体Vector(from )。chunk

  1. 基于 process1.chunk 的复制/粘贴:
def byteChunk(n: Int): Process1[ByteVector, ByteVector] = {

  def go(m: Int, acc: ByteVector): Process1[ByteVector, ByteVector] =
    if (m <= 0) {
      emit(acc) ++ go(n, ByteVector.empty)
    } else {
      def fallback = if (acc.nonEmpty) emit(acc) else halt
      receive1Or[ByteVector, ByteVector](fallback) { in =>
        go(m - 1, acc ++ in)
      }
    }

  go(n, ByteVector.empty)
}

Process有没有办法通过组合现有的'es来做同样的事情?

一个附带问题:可以repeat用来代替++ go? 是不是和上一个一样:

def byteChunk(n: Int): Process1[ByteVector, ByteVector] = {

  def go(m: Int, acc: ByteVector): Process1[ByteVector, ByteVector] =
    if (m <= 0) emit(acc)
    else ...

  go(n, ByteVector.empty).repeat
}
4

1 回答 1

0

我认为您可以使用take,lastscanMonoid

def byteChunk(n: Int): Process1[ByteVector, ByteVector] = {
  process1.take[ByteVector](n).scanMonoid.last ++ Process.suspend(go(n))
}

(或者如果您不想实施,则替换scanMonoid为类似的东西)。.scan(ByteVector.empty)((acc, x: ByteVector) => acc ++ x)Monoid[ByteVector]

它似乎也Process.repeat可以代替,++ Process.suspend(go(n))并且Process.repeat实施方式表明只要byteChunk(n)是纯的,它就会是真实的。

于 2015-05-10T19:52:49.070 回答