Section: 3.2 Infix operators

第 3.2 节 中缀运算符

Haskell has both identifiers, like x, and operators, like +. These are just two different types of syntax for variables. However, operators are by default used in infix notation.

Haskell 既有像 x 这样的标识符,也有像 + 这样的运算符。它们只是

变量的两种不同语法形式。不过,运算符默认以中缀记法使用。

Briefly, identifiers begin with a letter and may have numbers, _, and ' in them: x, xyz123, x'', xYz'_12a. The case of the first letter distinguishes variables from data constructors (or type variables from type constructors). An operator is a string of symbols, where :!#$%&*+./<=>?@\^| are all symbols. If the first character is : then the operator is a data constructor; otherwise it is an ordinary variable operator. The - and ~ characters may start a symbol but cannot be used after the first character. This allows a*-b to parse as a * - b instead of a *- b.

简而言之,标识符以字母开头,其中可以包含数字、_ 和 ':x、xyz123、

x''、xYz'_12a。首字母的大小写用来区分局部变量与数据构造器(或类型

变量与类型构造器)。运算符是一串符号,其中 :!#$%&*+./<=>?@\^| 都是

符号。如果首字符是 : ,该运算符就是数据构造器;否则它是普通的变量

运算符。- 和 ~ 可以开头,但不能出现在首字符之后的位置。这样 a*-b

就会被解析为 a * - b,而不是 a *- b。

Operators can be converted to identifiers by enclosing them in parens. This is required in signature declarations. Operators can be defined as well as used in the infix style:

把运算符用括号括起来就能转换为标识符。类型签名声明中必须这样做。

运算符既可以中缀使用,也可以中缀定义:

(++) :: [a] -> [a] -> [a]
[] ++ y = y
(x:xs) ++ y = x : (xs ++ y)

Table 2 (Page 54) of the report is invaluable for sorting out the precedences of the many predefined infix operators.

报告的表 2(第 54 页)在厘清众多预定义中缀运算符的优先级方面极其

有用。

e1 = "Foo" ++ "Bar"

This is the same function without operator syntax

这是同一个函数,只是不用运算符语法:

appendList :: [a] -> [a] -> [a]
appendList [] y = y
appendList (x:xs) y = x : appendList xs y
(.) :: (b -> c) -> (a -> b) -> (a -> c)
f . g = \x -> f (g x)
add1 :: Int -> Int
add1 x = x+1
e2 = (add1 . add1) 3

Section: 3.2.1 Sections

第 3.2.1 节 局部应用(section)

Sections are a way of creating unary functions from infix binary functions. When a parenthesized expression starts or ends in an operator, it is a section. Another definition of add1:

section 是一种从中缀二元函数创建一元函数的方法。当一个带括号的表达式

以运算符开头或结尾时,它就是一个 section。add1 的另一种定义:

add1' :: Int -> Int
add1' = (+ 1)
e3 = add1' 4

Here are a few section examples:

这里有几个 section 的例子:

e4 = map (++ "abc") ["x","y","z"]
e5 = map ("abc" ++) ["x","y","z"]

Section: 3.2.2 Fixity Declarations

第 3.2.2 节 结合性与优先级声明

We'll avoid any demonstration of fixity declarations. The Prelude contains numerous examples.

我们跳过 fixity 声明的演示。Prelude 中包含大量例子。