0

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?

  • 1
    You need parentheses to use an infix operator in prefix form: `($ 3) (4+)` should work and give you `7`. So would `($) (4+) 3` (note that the function comes first). In this case it's just a rather clumsy way of writing `4 + 3` – Robin Zigmond Feb 26 '19 at 08:19
  • 1
    As for the LYAH example, `($ 3)` is a "section" of the `$` operator - it's a function which, given a function, applies it to the number `3`. That is then `map`ped over a list of functions. – Robin Zigmond Feb 26 '19 at 08:21
  • if you want to use `$` as [prefix](https://wiki.haskell.org/Infix_operator) operator, you have to use `($)`, also see [section](https://wiki.haskell.org/Section_of_an_infix_operator) – wizzup Feb 26 '19 at 08:22

1 Answers1

12

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

melpomene
  • 84,125
  • 8
  • 85
  • 148
  • 1
    Haskell users are really supportive of [basic questions](https://stackoverflow.com/q/54849064/633183)! I find this refreshing, tbh. – Mulan Feb 26 '19 at 15:27