为什么以下编译:
{-# 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'])
Run Code Online (Sandbox Code Playgroud)
但改变main来此:
main = print (isList 42) >> print (isList [42])
Run Code Online (Sandbox Code Playgroud)
给出以下错误:
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)'
Run Code Online (Sandbox Code Playgroud)
isList肯定不是在Num课堂上吗?如果没有,为什么模棱两可?
mig*_*yte 12
问题不在于isList,而在于常量42.常量'a'具有一个具体类型的Char.常数42没有具体类型.
ghci> :t 42
42 :: Num a => a
Run Code Online (Sandbox Code Playgroud)
编译器需要具体类型.如果您将main更改为以下内容,它将起作用:
main = print (isList (42 :: Int)) >> print (isList [42 :: Int])
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
620 次 |
| 最近记录: |