0

If anyone can point me in the direction of why this works it would be greatly appreciated.

It was from my first f# lab in class.

How is add20 working when I have no parameters set to it(Problem 2C2).

////function that adds 10 to it

////Problem 2C1 ///
let k = 10
let add10 z k = z + k

////End Problem 2C1///    
////Problem 2C2 ///

let z = 20
let add20 = add10 z

////End Problem 2C2//
John Palmer
  • 25,356
  • 3
  • 48
  • 67
ezetreezy
  • 41
  • 5

1 Answers1

1

If you define an add function that looks like this (note that your add10 function is actually adding its two parameters, not the k constant defined on the previous line):

let add a b = a + b

The F# compiler will report that the function has a type int -> int -> int. Now, you can actually read this in two ways:

  1. int -> int -> int is a function that takes one int another int and produces int
  2. int -> (int -> int) is a function that takes int and returns int -> int.
    That is, you call it with one number. It returns a function that takes the other number and returns the total sum.

So, when you write add 32 10, you are using it in the way (1). When you write add 10, you get back a function as described in (2).

Tomas Petricek
  • 240,744
  • 19
  • 378
  • 553
  • So my add20, is in fact the second type you described. int -> (int ->int). May I ask if I am not providing any parameter to add20, how is it taking in an int? When I run it in F# interactive, it shows val add20 : (int -> int). Thank you for the help btw. – ezetreezy Feb 23 '15 at 21:48
  • @ezetreezy add20 is the result of a partial function application. The reason a function like Tomas's add function is `int -> int -> int` is that it can be thought of as a function that takes a single int parameter and returns another function that takes a single int parameter. Your `add20` is just such a function. That is the point that Tomas is making in his point #2 above. Another way of looking at it is that the parameter of add20 is implicit. This isn't a particularly idiomatic way of thinking about it, however. – phoog Feb 24 '15 at 18:48