无法使用Haskell的Aeson包生成任意json

时间:2016-02-04 14:45:09

标签: haskell aeson

我是一个Haskell newb,刚刚读完LYAH。我正在阅读this Aeson tutorial,但我在执行大多数代码示例时遇到了问题。例如,我在Scratch01.hs中有以下内容......

{-# LANGUAGE OverloadedStrings #-}

module Scratch01 where

import Data.Aeson
import GHC.Exts

val :: Value
val = Object $ fromList [
  ("numbers", Array $ fromList [Number 1, Number 2, Number 3]),
  ("boolean", Bool True) ]

...我试图像这样执行它

$ ghci --version
The Glorious Glasgow Haskell Compilation System, version 7.8.3
$ ghci -XOverloadedStrings
GHCi, version 7.8.3: http://www.haskell.org/ghc/  :? for help
Prelude> :load Scratch01.hs
[1 of 1] Compiling Scratch01        ( Scratch01.hs, interpreted )

Scratch01.hs:10:3:
    Couldn't match expected type ‘Item Object’
                with actual type ‘(t0, Value)’
    The type variable ‘t0’ is ambiguous
    In the expression:
      ("numbers", Array $ fromList [Number 1, Number 2, Number 3])
    In the first argument of ‘fromList’, namely
      ‘[("numbers", Array $ fromList [Number 1, Number 2, ....]),
        ("boolean", Bool True)]’
    In the second argument of ‘($)’, namely
      ‘fromList
         [("numbers", Array $ fromList [Number 1, Number 2, ....]),
          ("boolean", Bool True)]’

Scratch01.hs:10:33:
    Couldn't match expected type ‘Item Array’ with actual type ‘Value’
    In the expression: Number 1
    In the first argument of ‘fromList’, namely
      ‘[Number 1, Number 2, Number 3]’
Failed, modules loaded: none.
Prelude>

我一直在修改这些类型,但我很难过。我使用的是错误的GHC版本吗?

修改

我做了artyom建议的。这有效:

{-# LANGUAGE OverloadedStrings #-}

module Scratch01 where

import Data.Aeson
import qualified Data.HashMap.Lazy as HM
import qualified Data.Vector as V

val :: Value
val = Object $ HM.fromList [
  ("numbers", Array $ V.fromList [Number 1, Number 2, Number 3]),
  ("boolean", Bool True) ]

0 个答案:

没有答案