为什么不能读出正确的类型? [英] Why can't read deduce the correct type?
本文介绍了为什么不能读出正确的类型?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
在Haskell中,我可以使用 read
的字符串创建Haskell的值。
前奏>阅读1+ 3
4
我可以使用 fst 获取第一个元素
Prelude> fst(1,2)
1
然而,当我将 read
和 fst
获取第一个元素:
前奏> fst(读取(1,2))
<互动>:20:6:
使用'read'$ b $时无法推断(读取b0) b从上下文(读a)
被它的推断类型限制::读a => $< interactive>
:20:1-18
类型变量'b0'不明确
有什么问题?
解决方案
Num
,所以读取3+ 4
应用 +
到读取3
,如果编译器找不到你想要的,你必须指定类型阅读
,如下所示:
Prelude>让rd = read :: String->(Int,Int)
Prelude> rd(1,2)
In Haskell, I can make Haskell value from a string with read
.
Prelude> read "1" + 3
4
I can use fst
to get the first element
Prelude> fst (1,2)
1
However, I get an error when I combine read
and fst
to get the first element:
Prelude> fst (read "(1,2)")
<interactive>:20:6:
Could not deduce (Read b0) arising from a use of ‘read’
from the context (Read a)
bound by the inferred type of it :: Read a => a
at <interactive>:20:1-18
The type variable ‘b0’ is ambiguous
What's the problem?
解决方案
As read
is a polymorphic function, the read "3" + 4
works because the compiler know you want a Num
because you applied +
to read "3"
, If the compiler can't figure out what you want, you have to specify type of read
, like this:
Prelude> let rd = read :: String->(Int,Int)
Prelude> rd "(1,2)"
这篇关于为什么不能读出正确的类型?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文