user10661584
user10661584

Reputation:

Treating "$" as function application

I encountered this example while reading Learn You a Haskell for Great Good.

ghci> map ($ 3) [(4+), (10*), (^2), sqrt]  
[7.0,30.0,9.0,1.7320508075688772]  

I don't quite see how to treat $ as function application. Does that mean $ is an operator? But if so, how it will be nested with + or * in the example? I tried $ 3 4+, $ 4 + 3, but both raised parse error on input ‘$’. How to think of an expression like this in functional programming context?

Upvotes: 0

Views: 99

Answers (1)

melpomene
melpomene

Reputation: 85767

$ is indeed an operator, defined as:

f $ x = f x
-- or equivalently:
($) f x = f x

Your expression above is equivalent (by the definition of map) to:

[($ 3) (4 +), ($ 3) (10 *), ($ 3) sqrt]

The parentheses in ($ 3) and (4 +) are not optional. They're part of what's called an operator section. Basically, there are four ways you can use an infix operator (such as +):

  1. Between two arguments:

    x + y
    
  2. Only giving the first argument:

    (x +)
    -- like \y -> x + y
    
  3. Only giving the second argument:

    (+ y)
    -- like \x -> x + y
    
  4. No arguments:

    (+)
    -- like \x y -> x + y
    

($ 3) f evaluates to f $ 3 evaluates to f 3.

($ 3) (4 +) evaluates to (4 +) $ 3 evaluates to (4 +) 3 evaluates to 4 + 3 evaluates to 7.

Upvotes: 12

Related Questions