【发布时间】:2015-09-09 02:39:52
【问题描述】:
我需要使用严格和懒惰的 ByteStrings,因为这是由库选择预设的要求(happstack、base64、sha256、hexpat 等的混合)。在与“fromStrict”和类似的一些舞蹈之后,我最终得到了这个:
import qualified Data.ByteString.Char8 as S
import qualified Data.ByteString.Lazy.Char8 as L
class BString s where
lazy :: s -> L.ByteString
strict :: s -> S.ByteString
pack :: String -> s
text :: T.Text -> s
instance BString L.ByteString where
lazy = id
strict = S.concat . L.toChunks
pack = L.pack
text = L.fromStrict . TE.encodeUtf8
instance BString S.ByteString where
lazy = L.fromStrict
strict = id
pack = S.pack
text = TE.encodeUtf8
所以当库函数需要惰性字节字符串时,我只输入“lazy $”,或者在严格版本的情况下输入“strict $”。这很好用,虽然偶尔需要转换,但感觉就像我在这里发明了自行车。
那么,问题是这样的代码是否有更好的(更短、静态类型、更有效)替代方案?是否有图书馆试图统一惰性/严格处理?或者也许我做错了事,这被认为是一种不好的做法(你不应该在懒惰和严格之间转换)?
谢谢。
【问题讨论】:
标签: haskell bytestring