Reputation: 6993
I noticed as I was playing around with Haskell today that it is possible to do something like
($ 4) (> 3)
which yields True
. What is going on here? It'd be great to have some intuition.
My guess? It looks like the ($ 4)
is an incomplete function application, but where I'm confused is that $
is an infix operator, so shouldn't it look like (4 $)
? This doesn't compile, so clearly not, which leads me to believe that I don't really understand what's going on. The (>3)
term makes sense to me, because if you supply something like (\x -> x 4) (>3)
, you end up with the same result.
Upvotes: 10
Views: 507
Reputation: 53715
($ 4)
is the function that takes a function and applies 4
to it.
(> 3)
is the function that takes a number and checks if it is greater than 3.
So by giving the latter function to the former, you are essentially applying 4
to the function that checks if its input is greater than 3
, and thus you get True
.
Upvotes: 6
Reputation: 24822
You can partially apply an infix operator from either side. For commutative operators such as +
, it doesn't matter if you say (+ 1)
or (1 +)
, but for example for division you can supply either the dividend (5 /)
or the divisor (/ 5)
.
The function application operator takes a function as the left-hand operand and a parameter as the right-hand operand (f $ x
), so you can partially apply it either with a function (f $)
or with a parameter ($ x)
. So given
($ 4) (> 3)
You first partially apply the $-operator with the parameter 4
and supply it with the function (> 3)
. So what this essentially becomes is
(> 3) $ 4
Which is the same as (4 > 3)
.
Upvotes: 11
Reputation: 185801
($ 4)
is what's called a section. It's a way of partially applying an infix operator, but providing the right-hand side instead of the left. It's exactly equivalent to (flip ($) 4)
.
Similarly, (> 3) is a section.
($ 4) (> 3)
can be rewritten as
(flip ($) 4) (> 3)
which is the same as
flip ($) 4 (> 3)
which is the same as
(> 3) $ 4
And at this point, it should be clear that this boils down to (4 > 3)
.
Upvotes: 19