sof*_*sof 5 haskell infix-operator
以下所有表达式都得到评估而不会发生意外:
(+2) 1 -- 3
(*2) 1 -- 2
((-)2) 1 -- 1
(2-) 1 -- 1
(/2) 1 -- 0.5
(2/) 1 -- 2.0
Run Code Online (Sandbox Code Playgroud)
但不是这个:
(-2) 1 -- the inferred type is ambiguous
Run Code Online (Sandbox Code Playgroud)
GHC抛出一些关于推断类型不明确的错误.为什么?
这些带括号的表达式中的每一个但是(-2)(edit:和((-) 2))都是部分,即带有一个参数的函数并且"将它放在中缀运算符的缺失面上"(参见这个haskell.org wiki).
(-2)不是一个函数,而是一个数字(负2):
?> :t (-2)
(-2) :: Num a => a
Run Code Online (Sandbox Code Playgroud)
如果你写
?> (-2) 1
Run Code Online (Sandbox Code Playgroud)
看起来你正试图申请(-2)(一个号码)1(这是不可能的),GHCi理所当然地抱怨:
Could not deduce (Num (a0 -> t))
arising from the ambiguity check for ‘it’
from the context (Num (a -> t), Num a)
bound by the inferred type for ‘it’: (Num (a -> t), Num a) => t
at <interactive>:3:1-6
The type variable ‘a0’ is ambiguous
When checking that ‘it’
has the inferred type ‘forall a t. (Num (a -> t), Num a) => t’
Probable cause: the inferred type is ambiguous
Run Code Online (Sandbox Code Playgroud)
如果你想要一个2从另一个数字中减去的函数,你可以使用
(subtract 2)
Run Code Online (Sandbox Code Playgroud)
比较它的类型,
?> :t (subtract 2)
(subtract 2) :: Num a => a -> a
Run Code Online (Sandbox Code Playgroud)
到的(-2)(见上文).
将减号运算符括号将其转换为带有两个参数的正常(前缀)函数; 因此,((-) 2)它不是一个部分,而是一个部分应用的功能.
| 归档时间: |
|
| 查看次数: |
478 次 |
| 最近记录: |