为什么不可能在没有括号的Haskell中乘以负数 [英] Why it is impossible to multiply negative numbers in haskell without brackets

查看:117
本文介绍了为什么不可能在没有括号的Haskell中乘以负数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在haskell gchi中乘以 5 * -3 会给我和错误。但乘以 5 *(-3)即可。为什么需要括号?

  $ ghci 
GHCi,版本7.4.1:http://www.haskell .org / ghc /:?寻求帮助
加载包ghc-prim ...链接...完成。
加载包integer-gmp ...链接...完成。
加载程序包库...链接...完成。
前奏> 5 * -3

< interactive>:2:1:
优先解析错误
不能混合'*'[infixl 7]和前缀' - '[infixl 6]在相同的中缀表达式中
Prelude> 5 *(-3)
-15
前奏>


解决方案

由于一元减号运算符。不幸的是,这有点神奇。这是语言规范中一个奇怪的角落。



一元减号是语言中唯一的一元运算符。支持一元减法语法仅仅是为 negate 函数提供语法糖。



一方面,这个让我们让 - 7 -7 相同。另一方面,它打破了其他的一些东西,比如章节语法。



正如你所看到的,当写混合固定表达式时会造成混乱。
$ b

你需要用括号括起否定,如下所示:

  5 *(-3 )


Multiplying 5 * -3 in haskell gchi gives me and error. But multiplying 5 * (-3) works ok. Why are the brackets needed?

$ ghci
GHCi, version 7.4.1: http://www.haskell.org/ghc/  :? for help
Loading package ghc-prim ... linking ... done.
Loading package integer-gmp ... linking ... done.
Loading package base ... linking ... done.
Prelude> 5 * -3

<interactive>:2:1:
    Precedence parsing error
        cannot mix `*' [infixl 7] and prefix `-' [infixl 6] in the same infix expression
Prelude> 5 * (-3)
-15
Prelude>

解决方案

Because of how the unary minus operator is specified in Haskell. It is a bit magic, unfortunately. It's an odd corner of the language specification.

Unary minus is the only unary operator in the language. Support for unary minus syntax is simply to support syntactic sugar for the negate function.

On the one hand, this lets us make - 7 the same as -7. On the other hand, it breaks other things, like section syntax.

And as you see, it makes for confusion when writing mix fixed expressions.

You need to parenthesize the use of negate, as follows:

5 * (-3)

这篇关于为什么不可能在没有括号的Haskell中乘以负数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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