流式库中Sum编码的处理及字节流压缩适配问题
如何将压缩函数应用到Either ByteString ByteString的两个分支流?
没问题!这个需求其实很好实现,核心就是利用Either类型的**双函子(bifunctor)**特性——它天生支持同时对Left和Right两个分支应用函数。既然你需要对两个分支用同一个压缩函数,那就更直接了。
核心思路
Either类型的bimap函数(不同语言里可能叫类似的名字)接受两个函数:一个处理Left分支,一个处理Right分支。因为你要对两个分支用同一个压缩函数,直接把压缩函数传给两个参数就行。
代码示例(以Haskell为例)
假设你的压缩函数是compress :: ByteString -> ByteString,处理单个Either值和数据流的代码如下:
import Data.Either (bimap) import Data.ByteString (ByteString) -- 假设你用zlib之类的库实现压缩 import Codec.Compression.Zlib (compress) -- 处理单个Either ByteString ByteString值 compressEither :: Either ByteString ByteString -> Either ByteString ByteString compressEither = bimap compress compress -- 处理数据流(比如列表形式的流) compressEitherStream :: [Either ByteString ByteString] -> [Either ByteString ByteString] compressEitherStream = fmap compressEither -- 或者更简洁:fmap (bimap compress compress)
其他语言的等价实现
如果是用Scala这类支持Either双函子的语言,思路完全一致:
import java.nio.ByteBuffer import scala.util.Either // 模拟压缩函数 def compress(bs: ByteBuffer): ByteBuffer = { // 你的压缩逻辑,比如用Deflater ??? } // 处理单个Either值 def compressEither(either: Either[ByteBuffer, ByteBuffer]): Either[ByteBuffer, ByteBuffer] = either.bimap(compress, compress) // 处理流(比如List) def compressStream(stream: List[Either[ByteBuffer, ByteBuffer]]): List[Either[ByteBuffer, ByteBuffer]] = stream.map(compressEither)
为什么这能满足需求?
不管是错误状态的Left分支,还是正常状态的Right分支,只要是ByteString,都会被传入压缩函数处理。bimap保证了两个分支都被覆盖,不会遗漏任何一个,完全符合你“对任意分支进行压缩”的要求。
内容的提问来源于stack exchange,提问作者Sal
相关产品推荐
相关产品推荐

