Haskell只是使用read函数发出错误信号
任何人都可以解释,为什么阅读一个数字将其添加到另一个数字是有效的,但只读一个数字是无效的?
Prelude> read "5" + 3
8
Prelude> read "5"
:33:1:
No instance for (Read a0) arising from a use of `read'
The type variable `a0' is ambiguous
Possible fix: add a type signature that fixes these type variable(s)
Note: there are several potential instances:
instance Read () -- Defined in `GHC.Read'
instance (Read a, Read b) => Read (a, b) -- Defined in `GHC.Read'
instance (Read a, Read b, Read c) => Read (a, b, c)
-- Defined in `GHC.Read'
...plus 25 others
In the expression: read "5"
In an equation for `it': it = read "5"
为什么“5”不明确?
"5" 本身并不含糊 ,Haskell不知道你想read什么类型 。 read是一个函数,定义如下:
read :: Read a => String -> a 并且您可以定义支持Read类的多种类型。 例如, Int是Read一个实例,但也是Float ,您可以定义自己的类型,它是Read一个实例。 你可以例如定义你自己的类型:
data WeirdNumbers = Five | Twelve
然后定义一个instance Read WeirdNumbers ,其中您在Five上映射"5"等。现在, "5"映射到几种类型。
通过告诉Haskell您想要读取什么类型,您可以简单地解决问题。 喜欢:
Prelude> read "5" :: Int
5
Prelude> read "5" :: Float
5.0
read "5" + 3的原因是因为在这里你提供了一个3和一个(+) :: Num a => a -> a -> a 。 所以哈斯克尔的理由是“Well 3是一个Integer, +要求左边和右边的操作数是相同的类型,我知道我必须使用read来读取Integer。”
