0

I am quite confused about ($) in haskell.

when I type

:t ($)

in ghci. I will get

:($) :: (a -> b) -> a -> b

but, when I type

:t ($ 3)

I will get

($ 3) :: Num a => (a -> b) -> b

so, why ($) accept the second argument without any error?

septicmk
  • 89
  • 6
  • 1
    The `($)` function is indeed an ordinary Haskell function, but it’s also an infix operator, as are all functions whose names are entirely symbolic. Infix operators have special partial application syntax called *operator sections*, and you can read more about them here: https://wiki.haskell.org/Section_of_an_infix_operator – Alexis King Jul 23 '16 at 04:43
  • @Alexis King, [not so ordinary](http://www.mail-archive.com/glasgow-haskell-users@haskell.org/msg18923.html). – effectfully Jul 23 '16 at 10:01
  • 1
    @user3237465 I’m actually quite aware of that, yes, but bringing that up to a learner is only going to cause entirely unnecessary confusion. – Alexis King Jul 23 '16 at 19:14

1 Answers1

8

Well ($) is an operator, which is an infix function. It's definition is pretty straightforward (in fact the only thing that makes it interesting is its fixity, and I'm sure google has tons of resources on that):

($) :: (a -> b) -> a -> b
f $ x = f x

Like all operators, you can take sections of it by applying only the first or only the second argument. This might be more obvious with the addition (+) operator:

(+ 2) -- equivalent to \x -> x + 2
(2 +) -- equivalent to \x -> 2 + x

The same holds for ($ 3) - it is equivalent to \f -> f $ 3. The type of this function should be pretty clear then: its argument f has to be itself a function that takes a number and returns something else (f :: Num a => a -> b), and the whole function returns the same type as whatever f returns. That gives

(\f -> f $ 3) :: Num a => (a -> b) -> b

And consequently ($ 3) :: Num a => (a -> b) -> b.

Alec
  • 31,829
  • 7
  • 67
  • 114
  • If (3 $) then what would be the case ? I think it would not produce any result. Use with map (3$) [\x->x+10] , right ? – MD05 Nov 12 '16 at 00:28
  • 1
    `(3 $)` won't typecheck. `$` expects its first argument to be a function. – Alec Nov 12 '16 at 00:34