Collin O'Connor
Collin O'Connor

Reputation: 1351

F# Lambda Signature

I'm reading Programming F# by Chris Smith right now trying to figure out F# when i come across Lambadas. Here is a lambda from one of the examples

let generatePowerOfFunc base = (fun exponent -> base ** exponent);;

I get that it takes in something and returns a function, but what i don't get is the Signature of this function which is val generatePowerOfFunc : float -> float -> float

How does it have three floats instead of two? And when there's this method

let powerOfTwo = generatePowerOfFunc 2.0;;

It only has 2 floats val powerOfTwo : (float -> float)

Maybe Im not getting the whole type signature deal. Any help would be much appreciated. Thanks

Upvotes: 1

Views: 449

Answers (2)

kongo2002
kongo2002

Reputation: 1024

The function generatePowerOfFunc takes two arguments of type float and returns a float value:

val generatePowerOfFunc : float -> float -> float
//                        ^^^^^^^^^^^^^^
//                        arguments
//                                          ^^^^^
//                                          return value

The function powerOfTwo is like a partial function application that just takes one float argument (the exponent) and returns a float.

Upvotes: 2

Ramon Snir
Ramon Snir

Reputation: 7560

In addition to kongo2002:

The last item in the -> chain is the return type, not another argument. The first accepts two floats and returns a float, and the second accepts one float and returns one.

The idea of doing it like that, and not something like (float, float) : float, is that you can use a concept called "currying". generatePowerOfFunc is of type float -> float -> float, which is equivalent to float -> (float -> float), so we can give it a single float and get back a function of type float -> float (and we can give it another float, and get back a float).

This means that when you call generatePowerOfFunc 2. 4., you apply twice. Once you apply 2., and once you apply 4..

Upvotes: 3

Related Questions