Haskell: infixl, infixr, infix

栏目: 编程语言 · 发布时间: 7年前

内容简介:infix,infixl,infixr是Haskell中给运算符定义优先级操作用的。 例如:infixr是右结合,infixl是左结合,infix无左右优先性。优先级一共有 十个,0-9,数字越大越高,如果定义时省略了数字,则默认为9。

https://www.haskell.org/onlinereport/decls.html#fixity

infix,infixl,infixr是Haskell中给运算符定义优先级操作用的。 例如:

infixr 9 `op

infixr是右结合,infixl是左结合,infix无左右优先性。优先级一共有 十个,0-9,数字越大越高,如果定义时省略了数字,则默认为9。

预定义的优先级表格如下:

+----------+-----------+-----------------------------------+----------+
|          |  左结合   |              无结合               |  右结合  |
+----------+-----------+-----------------------------------+----------+
|     9    | !!        |                                   | .        |
+----------+-----------+-----------------------------------+----------+
|     8    |           |                                   | ^, ^^, **|
+----------+-----------+-----------------------------------+----------+
|     7    |*,/,`div`  |                                   |          |
+----------+-----------+-----------------------------------+----------+
|     6    |+, -       |                                   |          |
+----------+-----------+-----------------------------------+----------+
|     5    |           |                                   |:, ++     |
+----------+-----------+-----------------------------------+----------+
|     4    |           |==,/=,<,<=,>,>=,`elem`,`notElem`   |          |
+----------+-----------+-----------------------------------+----------+
|     3    |           |                                   | &&       |
+----------+-----------+-----------------------------------+----------+
|     2    |           |                                   | ||       |
+----------+-----------+-----------------------------------+----------+
|     1    | >>, >>=   |                                   |          |
+----------+-----------+-----------------------------------+----------+
|     0    |           |                                   |$,$!,`seq`|
+----------+-----------+-----------------------------------+----------+

根据上面的表,如果是 1 + 2 + 3 + 4 就等于 ((1 + 2) + 3) + 4 ,因为加法 符合结合律,所以我们不容易看出来,我们来看减法。

infixr `op`

op x y = x - y

main = do
    putStrLn $ show (5 - 3 - 2)
    putStrLn $ show (5 - 3 `op` 2)
$ runhaskell tryInfix.hs 
0
4

上述便是效果。

Haskell中自定义的操作符非常多,往往看源代码看的眼花缭乱,此外还需要非常注意优先级。


以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持 码农网

查看所有标签

本站部分资源来源于网络,本站转载出于传递更多信息之目的,版权归原作者或者来源机构所有,如转载稿涉及版权问题,请联系我们

The Algorithmic Beauty of Plants

The Algorithmic Beauty of Plants

Przemyslaw Prusinkiewicz、Aristid Lindenmayer / Springer / 1996-4-18 / USD 99.00

Now available in an affordable softcover edition, this classic in Springer's acclaimed Virtual Laboratory series is the first comprehensive account of the computer simulation of plant development. 150......一起来看看 《The Algorithmic Beauty of Plants》 这本书的介绍吧!

RGB转16进制工具
RGB转16进制工具

RGB HEX 互转工具

Base64 编码/解码
Base64 编码/解码

Base64 编码/解码

RGB CMYK 转换工具
RGB CMYK 转换工具

RGB CMYK 互转工具