[英]scalaz-stream: how to chunk with concatenation?
Is there an idiomatic way to chunk and concatenate? 有没有惯用的方式来分块和连接?
The ways that I've found (examples for bytes): 我发现的方式(字节示例):
import scodec.bits.ByteVector
def byteChunk(n: Int): Process1[ByteVector, ByteVector] =
process1.chunk(n).map(_.reduce(_ ++ _))
But the intermediate Vector
(from chunk
) isn't really needed in this case. 但是在这种情况下,实际上并不需要中间
Vector
(来自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)
}
Is there a way to do the same with combining the existing Process
'es? 是否可以通过合并现有
Process
来做到这一点?
A side question: could repeat
be used instead of ++ go
? 附带问题:可以
repeat
使用而不是++ go
吗? Is this the same as the previous: 这和以前的一样吗?
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
}
I think you could simplify this a bit using take
, last
and scanMonoid
我认为您可以使用
take
, last
和scanMonoid
简化此scanMonoid
def byteChunk(n: Int): Process1[ByteVector, ByteVector] = {
process1.take[ByteVector](n).scanMonoid.last ++ Process.suspend(go(n))
}
(or replace scanMonoid
with something like .scan(ByteVector.empty)((acc, x: ByteVector) => acc ++ x)
if you do not wish to implement Monoid[ByteVector]
). (或更换
scanMonoid
喜欢的东西.scan(ByteVector.empty)((acc, x: ByteVector) => acc ++ x)
,如果你不希望实现Monoid[ByteVector]
It also appears that Process.repeat
will work instead of ++ Process.suspend(go(n))
and the way Process.repeat
is implemented suggests it will be true as long as byteChunk(n)
is pure. 似乎还可以使用
Process.repeat
代替++ Process.suspend(go(n))
并且只要byteChunk(n)
是纯净的,实现Process.repeat
的方式就将是正确的。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.