haxl
haxl

Reputation: 53

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). When I try to execute that function, GHCI tells me the return value is

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?

Upvotes: 5

Views: 13790

Answers (3)

leftaroundabout
leftaroundabout

Reputation: 120751

Note that

\x y -> y+y

is syntactic sugar for

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

i.e. rather than saying “a lambda function of two arguments” you might say it's a function of only one argument. The return type just happens to be again a function.

This currying technique is really crucial for good Haskell code; 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. Without currying, I would have needed to write map (\x -> logBase(2,x)) [1,2,4,8,16].

Upvotes: 15

Adam Saltz
Adam Saltz

Reputation: 246

Look at it this way: if you had provided a value for y, you'd get an integer. If you don't provide a value, you'll get an expression which takes an integer (which you call y) and returns an integer, i.e. a function

Integer -> Integer

This works for named functions too. E.g.

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

You can check in ghci that the type of plus 1 is Int -> Int. In fact, this process works for any function in Haskell. You read more at the HaskellWiki.

Upvotes: 13

Eugene Sh.
Eugene Sh.

Reputation: 18381

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.

Upvotes: 6

Related Questions