简体   繁体   中英

Use of function application operator in Haskell

What does the following expression means in haskell?

($ 3)

ghci shows the following type

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

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

(@ x) for any operator @ is equivalent to \\a -> a @ x ; so ($ 3) is equivalent to \\f -> f $ 3 , ie 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

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM