Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

When should I use $ (and can it always be replaced with parentheses)?

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, like foo $ bar quux instead of foo (bar quux). Am I understanding it right? Is the latter form considered "bad style"?

like image 965
J Cooper Avatar asked Dec 28 '08 08:12

J Cooper


People also ask

When should a parentheses be used?

Parentheses are used to enclose incidental or supplemental information or comments. The parenthetical information or comment may serve to clarify or illustrate, or it may just offer a digression or afterthought. Parentheses are also used to enclose certain numbers or letters in an outline or list. 1.

Should I always be in parentheses?

Use a comma or parenthesis before the abbreviation unless it begins a sentence. You will want to use either a comma or parenthesis as a way of introducing the phrase that begins with i.e. or e.g. If you choose parentheses, be sure to include a comma after the abbreviation.

When should the use of parentheses be avoided?

Because they are so jarring to the reader, parentheses should be avoided whenever possible. If removing a parenthetical note changes the meaning of the sentence, it should not be in parentheses. Place a period outside a closing parenthesis if the material inside is not a sentence (such as this fragment).

What are () used for?

Parentheses are a pair of punctuation marks that are most often used to add additional nonessential information or an aside to a sentence. Parentheses resemble two curved vertical lines: ( ). A single one of these punctuation marks is called a parenthesis.


1 Answers

$ 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 list xs, and collects the results in a list. Contrast with sequence fs x which applies a list of functions fs to a single argument x and collects the results; and fs <*> xs which applies each function in the list fs to every element of the list xs.

like image 51
Apocalisp Avatar answered Sep 22 '22 15:09

Apocalisp