简体   繁体   English

Haskell:带有两个参数的匿名函数

[英]Haskell: anonymous function with two arguments

I have the following anonymous function: 我有以下匿名功能:

(\x y -> y+y) (5*(7+20))

As far as I understand anonymous functions, x should be (5*(7+20)) and y is not given (which is where it gets fishy). 据我所知的匿名函数,x应该是(5 *(7 + 20))并且没有给出y(这是它变得可疑的地方)。 When I try to execute that function, GHCI tells me the return value is 当我尝试执行该功能时,GHCI告诉我返回值是

Integer -> Integer

So obviously my interpretation is wrong here and I just can't see why. 显然我的解释在这里是错误的,我只是不明白为什么。 Can anyone explain to me what is happening here? 任何人都可以向我解释这里发生了什么?

Look at it this way: if you had provided a value for y, you'd get an integer. 这样看:如果你为y提供了一个值,你就得到一个整数。 If you don't provide a value, you'll get an expression which takes an integer (which you call y) and returns an integer, ie a function 如果你没有提供一个值,你将得到一个带整数的表达式(你称之为y)并返回一个整数,即一个函数

Integer -> Integer

This works for named functions too. 这也适用于命名函数。 Eg 例如

plus :: Int -> Int -> Int
plus x y = x + y

You can check in ghci that the type of plus 1 is Int -> Int . 您可以在ghci中检查plus 1的类型是Int -> Int In fact, this process works for any function in Haskell. 实际上,此过程适用于Haskell中的任何函数。 You read more at the HaskellWiki . 您可以在HaskellWiki上阅读更多内容

Giving a function of two arguments only one is resulting in a partial application of that function, whose result is a function of one (the remaining) argument. 赋予两个参数的函数只有一个导致该函数的部分应用 ,其结果是一个(剩余的)参数的函数。 While in your case the signature of the returned function is Integer -> Integer . 在您的情况下,返回函数的签名是Integer -> Integer

Note that 注意

\x y -> y+y

is syntactic sugar for 是语法糖

\x -> (\y -> y+y)

ie rather than saying “a lambda function of two arguments” you might say it's a function of only one argument. 即,而不是说“两个参数的lambda函数”,你可能会说它只是一个参数的函数。 The return type just happens to be again a function. 返回类型恰好是一个函数。

This currying technique is really crucial for good Haskell code; 这种currying技术对于良好的Haskell代码至关重要; partial application makes many things very concise without sacrificing readability. 部分应用程序使许多事情非常简洁而不牺牲可读性。 For example, 例如,

GHCi> map (logBase 2) [1,2,4,8,16]
[0.0, 1.0, 2.0, 3.0, 4.0]

Here I've used logBase as a function of a single argument ( 2 ), which gives me a simple number→number function that can be mapped over a list. 在这里,我使用logBase作为单个参数( 2 )的函数,这给了我一个简单的数字→数字函数,可以映射到列表。 Without currying, I would have needed to write map (\\x -> logBase(2,x)) [1,2,4,8,16] . 没有currying,我需要写map (\\x -> logBase(2,x)) [1,2,4,8,16]

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

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