为什么(.)称为中缀.而不是`(.)`
我了解到可以通过两种方式调用函数:前缀和中缀.例如,假设我创建了此函数:
I learned that functions can be invoked in two ways; prefix and infix. For example, say I've created this function:
example :: [Char] -> [Char] -> [Char]
example x y = x ++ " " ++ y
我可以这样称呼它为前缀:
I can call it prefix like so:
example "Hello" "World"
或像这样的中缀:
"Hello" `example` "World"
这两个都将导致表示字符串"Hello World"
的字符列表.
Both of which will result in the list of chars representing a string "Hello World"
.
但是,我现在正在学习有关函数组成的知识,并且遇到了如下定义的函数:
However, I am now learning about function composition, and have come across the function defined like so:
(.) :: (b -> c) -> (a -> b) -> a -> c
所以,说我想乘以3来求和.我会像这样写前缀调用:
So, say I was wanting to compose negate with multiplication by three. I would write the prefix invocation like:
negateComposedWithMultByThree = (.) negate (*3)
和infix调用类似:
And the infix invocation like:
negateComposedWithMultByThree = negate `(.)` (*3)
但是,虽然前缀调用可以编译,但infix调用却不会,而是显示错误消息:
But, whilst the prefix invocation compiles, the infix invocation does not and instead gives me the error message:
错误:解析输入`('
error: parse error on input `('
看来,要调用撰写中缀,我需要省略方括号并这样称呼它:
It seems, in order to call compose infix, I need to omit the brackets and call it like so:
negateComposedWithMultByThree = negate . (*3)
任何人都可以阐明这一点吗?为什么"Hello"`example`"World"
而否定`(.)`(* 3)
却为什么呢?
Can anyone shed any light on this? Why does "Hello" `example` "World"
whilst negate `(.)` (*3)
does not?
此外,如果我尝试使用这样的签名来实现自己的功能:
In addition, if I try to make my own function with a signature like this:
(,) :: Int -> Int
(,) x = 1
它无法编译,并显示错误:
It does not compile, with the error:
无效的类型签名(,):...的形式应为::"
"Invalid type signature (,) : ... Should be of form :: "
这里没有内容.关于标识符的解析,只有两种标识符具有不同的规则:by-default-infix和by-default-prefix.您可以知道是哪个,因为默认前缀标识符仅包含标点符号,而默认前缀标识符仅包含数字,字母,撇号和下划线.
There's nothing deep here. There's just two kinds of identifiers that have different rules about how they're parsed: by-default-infix, and by-default-prefix. You can tell which is which, because by-default-infix identifiers contain only punctuation, while by-default-prefix identifiers contain only numbers, letters, apostrophes, and underscores.
认识到默认并非总是正确的选择,该语言提供了与默认行为不同的转换.因此,有两种单独的语法规则,一种将默认的前缀标识符转换为前缀(添加括号),另一种将默认的前缀标识符转换为中缀(添加反引号).您不能嵌套这些转换:转换为前缀形式的默认前缀标识符不是默认前缀标识符.
Recognizing that the default isn't always the right choice, the language provides conversions away from the default behavior. So there are two separate syntax rules, one that converts a by-default-infix identifier to prefix (add parentheses), and one that converts a by-default-prefix identifier to infix (add backticks). You can not nest these conversions: a by-default-infix identifier converted to prefix form is not a by-default-prefix identifier.
就是这样.根本上没有什么有趣的-解析后它们全部成为函数应用程序-只是语法糖.
That's it. Nothing fundamentally interesting -- all of them become just function applications once parsed -- it's just syntax sugar.