2014-02-11 19 views
0

这里是我的尝试:如何将FromJSON实现为参数的类型传递给anoter函数?

decode :: String -> FromJSON a => BS.ByteString -> a 
decode fnm iFromJSONable = do 
    ymlData <- BS.readFile fnm 
    let ymlDecode :: Maybe iFromJSONable 
     ymlDecode = Data.Yaml.decode ymlData 
    return fromJust ymlDecode 

错误:

Couldn't match type `a' with `IO b0' 
    `a' is a rigid type variable bound by 
     the type signature for 
     Yaml.decode :: String -> FromJSON a => BS.ByteString -> a 
     at src\Yaml.hs:46:11 
Expected type: IO BS.ByteString -> (BS.ByteString -> IO b0) -> a 
    Actual type: IO BS.ByteString 
       -> (BS.ByteString -> IO b0) -> IO b0 
In a stmt of a 'do' block: ymlData <- BS.readFile fnm 

回答

3

您在这里混合了类型和值。您不能将类约束(如FromJSON)作为参数(iFromJSONable),然后在本地类型签名中使用它。

我想你想的:

decode :: FromJSON a => FilePath -> IO a 
decode fnm = do 
    ymlData <- BS.readFile fnm 
    let ymlDecode = Data.Yaml.decode ymlData 
    return (fromJust ymlDecode) 

您正在阅读从一个字符串指定的文件数据(FilePath仅仅是String的代名词)。您将得到一个IO动作,该动作可以产生任何类型a,这是FromJSON类的一个实例。哪种类型将由您使用decode函数的上下文来确定。

相关问题