Jör*_*tag 15

\它不是运算符,它是文字语法的一部分.更确切地说,它是两个文字语法的一部分:它表示一个lambda文字,它在字符串文字中用作转义字符.

运营商$在序言中被定义为

($) :: (a -> b) -> a -> b
f $ x = f x
Run Code Online (Sandbox Code Playgroud)

换句话说,它与空白完全相同,即只是普通的函数应用程序.但是,虽然函数应用程序是左关联的并且具有高优先级(实际上$是最高的),但是是右关联的并且具有低优先级.

当你有" f应用于g应用于h应用于x"的链时,这允许你省略括号,没有$运算符会像

f (g (h x))
Run Code Online (Sandbox Code Playgroud)

但与操作员可以写成

f $ g $ h x
Run Code Online (Sandbox Code Playgroud)

如果要将函数应用程序运算符本身作为参数传递给另一个函数,它也很有用.比如,您有函数列表和值列表,并且您希望将列表中的每个函数应用于另一个列表中的相应值:

zipWith ($) fs xs
Run Code Online (Sandbox Code Playgroud)


Don*_*art 7

这两个运营商做了什么:$ \

第一个($)是运营商,定义为:

-- | Application operator.  This operator is redundant, since ordinary
-- application @(f x)@ means the same as @(f '$' x)@. However, '$' has
-- low, right-associative binding precedence, so it sometimes allows
-- parentheses to be omitted; for example:
--
-- >     f $ g $ h x  =  f (g (h x))
--
-- It is also useful in higher-order situations, such as @'map' ('$' 0) xs@,
-- or @'Data.List.zipWith' ('$') fs xs@.

($)                     :: (a -> b) -> a -> b
f $ x                   =  f x
Run Code Online (Sandbox Code Playgroud)

它允许您编写具有较少括号的函数.

第二个标记\lambda抽象的Haskell语法的一部分- 匿名函数.

所以,例如

\x -> x + 1
Run Code Online (Sandbox Code Playgroud)

是一个将参数加1的函数.在Haskell报告中描述了lambda抽象的语法.