简体   繁体   English

haskell 记录参数或替代

[英]haskell record parameter or alternative

I am using aeson for parsing a https://jsonlines.org/ files.我正在使用aeson来解析https://jsonlines.org/文件。 Those files are dumps of Elastic Search indexes so the outermost structure is the same in all JSON objects.这些文件是 Elastic Search 索引的转储,因此所有 JSON 对象的最外层结构都是相同的。 If I understood right, record syntax do not allow parameter like in the Document record below, right?如果我理解正确,记录语法不允许像下面的Document记录中的参数,对吗? What would be the alternative?什么是替代方案?

One possible solution would be to use the JSON AST to read the JSON innermost objects and parse them latter, is it possible?一种可能的解决方案是使用JSON AST来读取 JSON 最里面的对象并稍后解析它们,这可能吗? How?如何?


import Data.Aeson
import qualified Data.ByteString.Lazy as L
import Data.Either
import Data.List
import GHC.Generics


data Suggestion =
  Suggestion { ... }
  deriving (Show, Generic)

data Synset =
  Synset { ...}
  deriving (Show, Generic)

data Document a =
  Document a
    { _index :: String
    , _type :: String
    , _id :: String
    , _score :: Int
    , _source :: a
    }
  deriving (Show, Generic)

readJ :: L.ByteString -> Either String Document
readJ s = eitherDecode s :: Either String Document

readJL :: FilePath -> IO [Either String Document]
readJL path = do
  content <- L.readFile path
  return (map readJ $ L.split 10 content)

Yes, record syntax does allow type parameters, you just shouldn't repeat them after the constructor name:是的,记录语法确实允许类型参数,你只是不应该在构造函数名称之后重复它们:

data Document a =
  Document
    { _index :: String
    , _type :: String
    , _id :: String
    , _score :: Int
    , _source :: a
    }
  deriving (Show, Generic)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM