如何将实现为FromJSON的类型作为参数传递给另一个函数?

时间:2014-02-11 08:45:13

标签: haskell interface

这是我的尝试:

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

1 个答案:

答案 0 :(得分: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函数的上下文。