更新时间:2023-02-25 18:09:35
\
不是一个运算符,它是字面语法的一部分。更确切地说,它是两个文字语法的一部分:它表示一个lambda文字,它在字符串文字中用作转义字符。
运算符 $
在前奏中被定义为
($):: (a - > b) - > a - > b
f $ x = fx
换句话说, em>与空格相同,即只是简单的函数应用。 ,而函数应用程序是左关联的并且具有高优先级(实际上最高), $
是右关联的,并且具有低优先级。
这样可以在你将 f 这样的链应用于时省略括号。应用于
x
的 h
,其中 > $
运算符会写成像
f(g(hx))
但用运算符可以写成
f $ g $ hx
如果您想通过函数应用程序运算符本身作为另一个函数的参数。比如说,你有函数列表和值列表,你想将列表中的每个函数应用到另一个列表中的对应值:
zipWith($)fs xs
Can someone explain to me with simple words what those two operators do:
$
\
\
is not an operator, it is part of the literal syntax. More precisely, it is part of two literal syntaxes: it denotes a lambda literal and it serves as an escape character in string literals.
The operator $
is defined in the prelude as
($) :: (a -> b) -> a -> b
f $ x = f x
In other words, it does exactly the same thing as whitespace does, namely just plain function application. However, while function application is left-associative and has high precedence (the highest, in fact), $
is right-associative and has low precedence.
This allows you to omit parentheses when you have chains like "f
applied to g
applied to h
applied to x
", which without the $
operator would be written like
f (g (h x))
but with the operator can be written as
f $ g $ h x
It is also useful if you want to pass the function application operator itself as an argument to another function. Say, you have list of functions and a list of values and you want to apply every function in the list to the corresponding value in the other list:
zipWith ($) fs xs