4 ms·
Some extra background on `$`, for the curious: Function application in Haskell is expressed like so: > f x Where `f` is a function, and `x` is it's argument.
by cstrahan 12y ago
Some extra background on `$`, for the curious:
Function application in Haskell is expressed like so:
> f x
Where `f` is a function, and `x` is it's argument. Function application is left associative, so
> f x y
Is equivalent to
> (f x) y
In this case, `(f x)` yields a new function, to which `y` is then applied (see http://en.wikipedia.org/wiki/Currying http://en.wikipedia.org/wiki/Currying).
The function `$` that you mention is just application:
> f $ x = f x
So, using `$` infix like so
> f $ x
Is equivalent to
> f x
And likewise
> delay (1/4) $ p1
is equivalent to
> (delay (1/4)) p1
with extra parenthesis to make associativity clear.
This begs the question: when is `$` ever a useful function? There are two cases that come to mind:
1) Precedence. `$` has the lowest precedence of any function, and can thus be used to omit otherwise necessary parens; this
> f (g x)
is equivalent to
> f $ g x
2) Use in higher order functions. Imagine you have a function `all` that takes a predicate function `f` and a list of values `xs` and returns `True` if `f x` returns `True` for all `x` in `xs`. So `all (> 3) [4,5,6]` returns `True`. But, imagine now that you have a list of predicates and one value: can you still make use of `all` in this case?
Yes, you could do something like this:
> all (\f -> f 42) [even, (> 3), (< 100)]
But that's a little verbose. If we look at `(\f -> f 42)`, all it's doing is taking a function and immediately applying `42` to it - hey, that sounds like `$` if it was partially applied to `42`! Here's a simpler version of the previous expression:
> all ($ 42) [even, (> 3), (< 100)]
So that's pretty much all there is to `$` and why one may omit it in the original expression.