0

默认情况下,AesonencodeencodePretty不将尾随换行符附加到ByteString. 即,在 vim 中查看生成的文件时,我看到了[noeol]指示符。

将换行符附加到文件的高性能/惯用方式是什么?

这是一个SSCCEMain.hs

{-# LANGUAGE DeriveGeneric #-}

import           Data.Aeson
import           Data.Aeson.Encode.Pretty
import           GHC.Generics
import qualified Data.ByteString.Lazy as L
import qualified Data.ByteString.Internal  as BS

data ExampleRecord =
  ExampleRecord {
       field1 :: String
     , field2 :: String
       } deriving (Show, Generic)

instance ToJSON ExampleRecord

main = L.writeFile "foo.json" $ encodePretty (ExampleRecord "a" "b")

附带myproj.cabal文件:

name:                myproj
version:             0.1.0.0
build-type:          Simple
cabal-version:       >=1.10

executable emit-json
  main-is:             Main.hs
  build-depends:
      base >=4.8 && <4.9
    , aeson
    , aeson-pretty
    , bytestring
  default-language:    Haskell2010

我可以foo.json使用snocfrom 函数ByteString添加换行符,将最后一行更改为Main.hs

main = L.writeFile "foo.json" $ encodePretty (ExampleRecord "a" "b") `L.snoc` BS.c2w '\n'

但是,snoc文档将其描述为 O(n) 操作。是否应该有办法在恒定时间内附加这个换行符?

4

0 回答 0