Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Meaning of `$` when used as argument to map

I understand that the $ operator is for avoiding parentheses. Anything appearing after it will take precedence over anything that comes before.

I am trying to understand what it means in this context:

map ($ 3) [(+),(-),(/),(*)]

With the following code:

instance Show (a -> b) where
  show a = function

main = putStrLn $ show $ map ($ 3) [(+),(-),(/),(*)]

The output is

["function", "function", "function", "function"]

This doesn't help me understand the meaning of the $ here. How can I display more helpful output?


1 Answers

($) :: (a -> b) -> a -> b is a function that takes a function as first parameter, and a value as second and returns the value applied to that function.

For example:

Prelude> (1+) $ 2
3

The expression ($ 3) is an example of infix operator sectioning [Haskell-wiki]. ($ 3) is short for \f -> f $ 3, or simpler \f -> f 3. It thus is a function that takes a function and applies 3 to that function.

For your expression:

map ($ 3) [(+),(-),(/),(*)]

the output is thus equivalent to:

[(3+), (3-), (3/), (3*)] :: Fractional a => [a -> a]

Since (+), (-), (*) :: Num a => a -> a -> a work with types that are members of the Num typeclass, and (/) :: Fractional a => a -> a -> a works with types that are members of the Fractional type class, and all Fractional types are num types as well, 3 is here a Fractional type, and the list thus contains functions that are all of the type a -> a with a a member of Fractional.

How can I display more helpful output?

The compiler does not keep track of the expressions, as specified in the Haskell wiki page on Show instance for functions [Haskell-wiki].

The Haskell compiler doesn't maintain the expressions as they are, but translates them to machine code or some other low-level representation. The function \x -> x - x + x :: Int -> Int might have been optimized to \x -> x :: Int -> Int. If it's used anywhere, it might have been inlined and optimized to nothing. The variable name x is not stored anywhere. (...)

So we can not "look inside" the function and derive an expression that is human-readable.

like image 152
Willem Van Onsem Avatar answered Sep 05 '25 01:09

Willem Van Onsem