什么时候应该使用$(并且总是可以用括号替换)? [英] When should I use $ (and can it always be replaced with parentheses)?
问题描述
从我正在阅读的内容中, $
被描述为对其参数应用函数。然而,在Lisp中它看起来并不像(apply ...)
,因为它是一个二元运算符,所以看起来它唯一的作用是有时避免使用括号,例如 foo $ bar quux
而不是 foo(bar quux)
。我理解它吗?后面的形式是否被认为是坏风格?
如果开启和关闭的距离之间的距离大于良好的可读性权限,或者您有多层嵌套括号,则优先选择括号。
例如
p> i(h(g(fx)))
可以被重写
i $ h $ g $ fx
换句话说,它表示右联合函数应用程序。这是很有用的,因为普通的函数应用程序与左边相关联,即以下
ihgfx
...可以改写如下
(((ih)g)f)x
其他方便的用途
$($)
函数包括用它压缩一个列表:
zipWith($)fs xs
这适用于函数列表中的每个函数
fs
添加到列表xs
中的相应参数中,并将结果收集到列表中。与序列fs x
相比,它将函数列表fs
应用于一个参数x
并收集结果;和fs< *> xs
将列表fs
中的每个函数应用于列表xs
的每个元素。From what I'm reading,
$
is described as "applies a function to its arguments." However, it doesn't seem to work quite like(apply ...)
in Lisp, because it's a binary operator, so really the only thing it looks like it does is help to avoid parentheses sometimes, likefoo $ bar quux
instead offoo (bar quux)
. Am I understanding it right? Is the latter form considered "bad style"?解决方案
$
is preferred to parentheses when the distance between the opening and closing parens would otherwise be greater than good readability warrants, or if you have several layers of nested parentheses.For example
i (h (g (f x)))
can be rewritten
i $ h $ g $ f x
In other words, it represents right-associative function application. This is useful because ordinary function application associates to the left, i.e. the following
i h g f x
...can be rewritten as follows
(((i h) g) f) x
Other handy uses of the
($)
function include zipping a list with it:zipWith ($) fs xs
This applies each function in a list of functions
fs
to a corresponding argument in the listxs
, and collects the results in a list. Contrast withsequence fs x
which applies a list of functionsfs
to a single argumentx
and collects the results; andfs <*> xs
which applies each function in the listfs
to every element of the listxs
.这篇关于什么时候应该使用$(并且总是可以用括号替换)?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!