Reputation: 677
What does the following expression means in haskell?
($ 3)
ghci shows the following type
($ 3) :: Num a => (a -> b) -> b.
Upvotes: 3
Views: 195
Reputation: 4506
Another way to look at it is
($) :: (a -> b) -> a -> b
3 :: Num a => a
and when you "insert 3" in the ($)
it will become
($ 3) :: Num a => (a -> b) -> b.
due to that you no longer need to supply the a, but the function you need to supply is now restricted to num, since the 3 can be any numeric type.
This is at least how I look at functions in Haskell, like substitution in algebra.
Upvotes: 3
Reputation: 116139
($ 3)
is a section, and is equivalent to \f -> f 3
, which takes a function argument and applies it to 3.
If we considered 3
to be an integer, we would have that the type of f
is Int -> b
(for any b
), so the type of ($ 3)
would be (Int -> b) -> b
.
Things in Haskell are a bit more complex, since 3
can be of any numeric type, so we don't really need f :: Int -> b
, it's enough if f :: a -> b
where a
is a numeric type.
Hence we get ($ 3) :: Num a => (a -> b) -> b
.
Upvotes: 8
Reputation:
(@ x)
for any operator @
is equivalent to \a -> a @ x
; so ($ 3)
is equivalent to \f -> f $ 3
, i.e. a function that applies any function you pass it to 3
. This syntax is called "sections".
> let f = ($ 3)
> f show
"3"
> f square
9
Upvotes: 6