Granville Barnett

Functions as values in F#

One of the things I love about functions in functional languages like F# and Haskell is that they are treated like values. 

#light

let multiply a b = a * b

The multiply function has the signature Int -> Int -> Int where int is Int32.  In Haskell you would explicitly define the signature of the function, but you don't in F#.

If you run the below example first in F# interactive you will see the signature of the function changing until all of its function parameters have been satisfied.

#light

let multiply a b = a * b
let m1 = multiply 3 
let m2 = m1 3

values1

You can see that m1 is a function that expects a single int argument, and m2 simply holds the result of the multiply function.

  1. We define a function multiply which expects 2 int arguments and returns an int.
  2. the value of m1 is a function that expects a single argument as we have already provided one of the two arguments required by the multiply function.
  3. The value of m2 is simply a single integer (9) as we have invoked the function m1 (int -> int) passing in the missing argument 3.

If you print out the value of m2 you will see 9.

Posted: Sep 19 2007, 05:55 PM by gbarnett
Filed under:

Comments

No Comments