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

前端 未结 5 941
伪装坚强ぢ
伪装坚强ぢ 2021-01-04 21:31

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

5条回答
  •  离开以前
    2021-01-04 22:02

    $ 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.

提交回复
热议问题