繁体   English   中英

Haskell Wreq - 无法匹配预期类型“GHC.Exts.Item a0”

[英]Haskell Wreq - Couldn't match expected type ‘GHC.Exts.Item a0’

运行以下代码时遇到类型错误:

runPost :: IO String
runPost = do
    res <- post "http://httpbin.org/post" ["num" := (31337 :: Int)]
    return $ show res

错误如下:

• Couldn't match expected type ‘GHC.Exts.Item a0’
                  with actual type ‘FormParam’
      The type variable ‘a0’ is ambiguous
    • In the expression: "num" := (31337 :: Int)
      In the second argument of ‘post’, namely
        ‘["num" := (31337 :: Int)]’
      In a stmt of a 'do' block:
        res <- post "http://httpbin.org/post" ["num" := (31337 :: Int)]

当我检查 ghci 中:=的类型时,我看到了正确的类型:

*Main Network.Wreq> :t (:=)
(:=)
  :: FormValue v =>
     Data.ByteString.Internal.ByteString -> v -> FormParam

我想知道的是为什么GHC.Exts.Item在我运行编译器时显示为期望类型。 我只从Network.Wreq导入了我正在使用的函数。 任何想法可能会发生什么?

很明显(对编译器,如果不是对你的同胞) ("num" := (31337 :: Int)) :: FormParam 编译器不清楚(以及您需要帮助它做出决定)是[x]的类型,一旦x已知为FormParam

Item “类型”实际上是一个类型族,来自IsList类; 并且IsList连接来自打开OverloadedLists扩展。

这是一个导致基本相同错误的最小程序,它应该更清楚发生了什么:

{-# LANGUAGE OverloadedLists #-}

main :: IO ()
main = print [True]
    • Couldn't match expected type ‘GHC.Exts.Item a0’
                  with actual type ‘Bool’
      The type variable ‘a0’ is ambiguous
    • In the expression: True
      In the first argument of ‘print’, namely ‘[True]’
      In the expression: print [True]
  |
4 | main = print [True]
  |               ^^^^

print函数的类型为Show a => a -> IO () 如果未启用OverloadedLists扩展,则表达式[True]类型为[Bool] ,一切都会好起来的。 但是启用OverloadedLists扩展后,表达式[True]改为具有类型(GHC.Exts.IsList l, GHC.Exts.Item l ~ Bool) => l 统一后, print [True]最终基本上有类型(Show a, GHC.Exts.IsList a, GHC.Exts.Item a ~ Bool) => IO () 请注意,类型变量a没有出现在=>右侧的任何位置,这使得它成为一个不明确的类型。 为了使不确定性更具体的,请注意,除了[Bool]类型NonEmpty Bool用于也会工作, a在那里。 编译器不知道您想要哪个并且不想猜测,所以它会给您那个错误。 为了解决这个问题,添加一个类型注解,像这样: main = print ([True] :: [Bool])

对于您问题中的实际问题,唯一的区别是您拥有Postable类型类而不是Show ,以及FormParam类型而不是Bool 您可以通过将错误行替换为res <- post "http://httpbin.org/post" (["num" := (31337 :: Int)] :: [FormParam])来解决您的问题。

暂无
暂无

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

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