任何人都可以解释一下,为什么读取一个数字将其添加到另一个数字是有效的,尽管只读一个数字是无效的?
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 -> aRun Code Online (Sandbox Code Playgroud)
您可以定义支持Read该类的多种类型.例如,Int是一个实例Read,但Float您也可以定义自己的实例类型Read.例如,您可以定义自己的类型:
data WeirdNumbers = Five | Twelve
Run Code Online (Sandbox Code Playgroud)
然后定义instance Read WeirdNumbers你映射的"5"位置Five,等等.现在"5"可以映射几种类型.
您可以通过告诉Haskell您想要阅读的类型来解决问题.喜欢:
Prelude> read "5" :: Int
5
Prelude> read "5" :: Float
5.0
Run Code Online (Sandbox Code Playgroud)
read "5" + 3顺便说一下工作的原因是因为在这里你提供了一个3和一个(+) :: Num a => a -> a -> a.所以Haskell的理由是"Well 3是一个整数,并且+要求左右操作数属于同一类型,我知道我必须使用read它来读取整数."