简体   繁体   English

在Haskell中使用函数应用程序运算符

[英]Use of function application operator in Haskell

What does the following expression means in haskell? 以下表达式在haskell中的含义是什么?

($ 3)

ghci shows the following type ghci显示以下类型

($ 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. ($ 3)是一个部分,相当于\\f -> f 3 ,它接受一个函数参数并将其应用于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 . 如果我们认为3是一个整数,我们会得到f的类型是Int -> b (对于任何b ),所以($ 3)的类型将是(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. Haskell中的东西有点复杂,因为3可以是任何数字类型,所以我们不需要f :: Int -> b ,如果f :: a -> b就足够f :: a -> b其中a是数字类型。

Hence we get ($ 3) :: Num a => (a -> b) -> b . 因此我们得到($ 3) :: Num a => (a -> b) -> b

(@ x) for any operator @ is equivalent to \\a -> a @ x ; (@ x)对于任何运算符@相当于\\a -> a @ x ; so ($ 3) is equivalent to \\f -> f $ 3 , ie a function that applies any function you pass it to 3 . 所以($ 3)相当于\\f -> f $ 3 ,即一个函数,它将你传递给它的任何函数都应用到3 This syntax is called "sections". 此语法称为“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”时它就会变成

($ 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. 由于您不再需要提供a,但您需要提供的功能现在限制为num,因为3可以是任何数字类型。

This is at least how I look at functions in Haskell, like substitution in algebra. 这至少是我如何看待Haskell中的函数,比如代数中的替换。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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