gpt4 book ai didi

Haskell - 模棱两可的类型变量,为什么?

转载 作者:行者123 更新时间:2023-12-04 06:20:51 25 4
gpt4 key购买 nike

为什么以下编译:

{-# LANGUAGE FlexibleInstances #-}
{-# LANGUAGE OverlappingInstances #-}

class IsList a where
isList :: a -> Bool

instance IsList a where
isList x = False

instance IsList [a] where
isList x = True

main = print (isList 'a') >> print (isList ['a'])

但改变 mainthis :
main = print (isList 42) >> print (isList [42])  

给出以下错误:
Ambiguous type variable `a0' in the constraints:
(Num a0) arising from the literal `42' at prog.hs:13:22-23
(IsList a0) arising from a use of `isList' at prog.hs:13:15-20
Probable fix: add a type signature that fixes these type variable(s)
In the first argument of `isList', namely `42'
In the first argument of `print', namely `(isList 42)'
In the first argument of `(>>)', namely `print (isList 42)'
isList肯定不在 Num上课是吗?如果不是,为什么会模棱两可?

最佳答案

问题不在于 isList,而在于常量 42。常量 'a' 有一个具体的 Char 类型。常数 42 没有具体类型。

ghci> :t 42
42 :: Num a => a

编译器需要一个具体的类型。如果您将 main 更改为以下内容,它将起作用:
main = print (isList (42 :: Int)) >> print (isList [42 :: Int])  

关于Haskell - 模棱两可的类型变量,为什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16052092/

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