OK, it's been a long day and my brain may not function at Haskell level, but I just cannot understand one example from 'Learn You a Haskell'.
The section is called Function Application with $, and there is example of how $
may be defined:
($) :: (a -> b) -> a -> b
f $ x = f x
So far everything is clear. I understand all examples in the section, except for the last one:
ghci> map ($ 3) [(4+), (10*), (^2), sqrt]
[7.0,30.0,9.0,1.7320508075688772]
Here we map ($ 3)
across list of functions and get result of application of those functions to 3
. But how is this possible?
From the first code snippet it's clear that first argument is a function, we can even write:
*Main> ($) sqrt 4
2.0
Now ($ 3)
is a partial application of function $
, but 3
goes on function's position! So 3
is supposed to be a function or what?
There is another mystery: what the heck is (4+)
? I know that (+4)
is a partial application of function +
, so (4+)
should be partial application of function 4
? Nonsense. What sort of trick works here?
($ 3)
and(+ 4)
aren't partial applications - they're operator sections. A partial application would look like(($) 3)
or((+) 4)
.An operator section of the form
(? x)
(where?
stands for an arbitrary infix operator) binds the right operand of the operator, i.e. it is equivalent to\y -> y ? x
. Likewise the operator section(x ?)
binds the left operand and is thus equivalent to partial application.