【发布时间】:2019-03-16 15:30:48
【问题描述】:
我正在尝试编写一个期望提供 Json 字符串作为输入的 Haskell 程序。预期的 Json 是 Person 对象的列表。我想处理当用户默认为空列表的 Json 时没有提供输入的情况。
好像我遇到了 ByteString 和 String 之间的类型转换问题。我确实打开了OverloadedStrings,但在这里似乎没有帮助。这是简化的代码。
{-# LANGUAGE OverloadedStrings #-}
import GHC.Generics
import System.Environment
import Data.Aeson
import Data.Maybe (fromMaybe, listToMaybe)
import Data.Text (Text)
data Person = Person { pName :: Text, pAge :: Int } deriving (Show,
Generic)
instance ToJSON Person
instance FromJSON Person
main :: IO (Maybe [Person])
main = do
args <- getArgs
arg1 <- pure $ (fromMaybe "[]" (listToMaybe args))
-- let arg1 = "[{\"pName\": \"James\", \"pAge\": 30}]"
return $ decode arg1 :: IO (Maybe [Person])
我得到的错误是:
• Couldn't match type ‘[Char]’
with ‘Data.ByteString.Lazy.Internal.ByteString’
Expected type: Data.ByteString.Lazy.Internal.ByteString
Actual type: String
• In the first argument of ‘decode’, namely ‘arg1’
In the second argument of ‘($)’, namely ‘decode arg1’
In a stmt of a 'do' block:
return $ decode arg1 :: IO (Maybe [Person])
如果我取消注释 let arg1 以模拟 arg1 应该是什么,则代码编译。
【问题讨论】:
-
arg1 <- pure $ ...可以写成let arg1 = ...。