gpt4 book ai didi

haskell - 约束中的模糊类型变量 `a0'

转载 作者:行者123 更新时间:2023-12-03 11:34:29 25 4
gpt4 key购买 nike

我正在尝试通过 YesNo来自 Learn You a Haskell for Great Good! 的示例书。

这是我的源代码:

module Main where

main :: IO ()

main = putStrLn ( show (yesno 12) )

class YesNo a where
yesno :: a -> Bool


instance YesNo Bool where
yesno b = b

instance YesNo [a] where
yesno [] = False
yesno _ = True


instance YesNo Int where
yesno 0 = False
yesno _ = True

当我执行此代码时,会发生以下异常:
Ambiguous type variable `a0' in the constraints:
(YesNo a0) arising from a use of `yesno'
at /Users/mkhadikov/Projects/personal/haskell/hello-world/yesno.hs:5:25-29
(Num a0) arising from the literal `12'
at /Users/mkhadikov/Projects/personal/haskell/hello-world/yesno.hs:5:31-32
Probable fix: add a type signature that fixes these type variable(s)
In the first argument of `show', namely `(yesno 12)'
In the first argument of `putStrLn', namely `(show (yesno 12))'
In the expression: putStrLn (show (yesno 12))

你能解释一下这段代码有什么问题吗?

最佳答案

问题是它不知道 12 是什么类型!它可以是带有 Num 实例的任何类型:

GHCi> :t 12
12 :: Num a => a

你需要直接指定你想要的类型:试试 putStrLn (show (yesno (12 :: Int))) .

你问,为什么 GHC 不能选择 Int,因为没有其他选择可行?好问题。答案是使用 Haskell 的类型类系统,添加一个实例永远不会使现有的正确程序无效或改变它们的行为。 (这被称为开放世界假设。)如果它确实选择了 Int,那么如果添加 instance YesNo Integer 会发生什么? ?选择会变得模棱两可,你的程序就会崩溃!

因此,当您想将这样的类型类与多态值一起使用时,您必须更准确地指定您所指的类型。这在实践中不应该出现太多,因为通常会有一些周围的上下文来强制类型成为你想要的;受此影响的主要是数字文字。

关于haskell - 约束中的模糊类型变量 `a0',我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8546335/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com