为什么一元减算子在这个表达式中存在问题:( - 2)1? [英] Why is the unary minus operator problematic in this expression: (- 2) 1?

查看:101
本文介绍了为什么一元减算子在这个表达式中存在问题:( - 2)1?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

以下所有表达式的评估都不会有任何不妥:

(+ 2)1 - - 3
(* 2)1 - 2
(( - )2)1 - 1
(2-)1 - 1
(/ 2)1 - - 0.5
(2 /)1 - 2.0

但这不是: p>

( - 2)1 - 推断的类型不明确

GHC会抛出一些关于推断类型不明确的错误。为什么?

解决方案

这些括号表达式中的每一个,但( - 2) (编辑:和(( - )2))是部分,即函数采用一个参数,并且将它放在infix operator(见 haskell.org wiki )。



( - 2)不是函数,而是数字(负数2): p>

 λ> :t(-2)
(-2):: Num a => a

如果你写了

 λ> (-2)1 

看起来您正在尝试应用( -2)(一个数字)为 1 (这是不可能的),GHCi正确地抱怨:

 无法推论(Num(a0  - > t))
从上下文中的'it'
的歧义性检查(a - > t),Num a)
由'it'的推断类型限定:(Num(a-> t),Num a)=> t
at< interactive>:3:1-6
类型变量'a0'不明确
当检查'it'
具有推断类型'forall a t 。 (Num(a→t),Num(a)=> t'
可能的原因:推断的类型不明确

如果您想要一个减去您可以使用

 (减去2)$  2  b $ b  

比较其类型,

 λ> :t(减2)
(减2):: Num a => a - > a

( - 2) (见上文)。



术语附录(OP编辑后)



用括号括起minus运算符将其变成一个具有两个参数的普通(前缀)函数;因此(( - )2)不是一个部分,而是一个部分应用的函数。


All of the following expressions get evaluated without mishap:

(+2) 1 -- 3
(*2) 1 -- 2
((-)2) 1 -- 1
(2-) 1 -- 1   
(/2) 1 -- 0.5
(2/) 1 -- 2.0

but not this one:

(-2) 1 -- the inferred type is ambiguous

GHC throws some error about the inferred type being ambiguous. Why?

解决方案

Each of these parenthesized expressions but (-2) (edit: and ((-) 2)) are sections, i.e. functions that take one argument and "put it on the missing side of the infix operator" (see this haskell.org wiki).

(-2) is not a function, but a number (negative 2):

λ> :t (-2)
(-2) :: Num a => a

If you write

λ> (-2) 1

it looks like you're trying to apply (-2) (a number) to 1 (which is not possible), and GHCi rightfully complains:

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

If you want a function that subtracts 2 from another number, you can use

(subtract 2)

Compare its type,

λ> :t (subtract 2)
(subtract 2) :: Num a => a -> a

to that of (-2) (see above).


Terminology addendum (after OP's edit)

Parenthesizing the minus operator turns it into a normal (prefix) function that takes two arguments; therefore ((-) 2) is not a section, but a partially applied function.

这篇关于为什么一元减算子在这个表达式中存在问题:( - 2)1?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆