Reputation: 11649
This is a simple implimentation of factorial function in F#
let rec fact =function
| 0->1
| n-> n * fact(n-1);;
fact 5
1- what is the role of the rec
word here?
2- fact is the function, but it is never mentioned that it can have a parameter.
So technically it should face with an error, since in the signature
(let rec fact
) there is no parameter defined for it.
So how does it works?
Upvotes: 2
Views: 84
Reputation: 125650
1) rec
is used to mark function as recursive. Without it you would not be able to call it from within the function implementation. Read more on MSDN: Recursive Functions: The rec Keyword (F#)
2) let rec fact = function
is a shortcut for:
let rec fact argument =
match argument with
| 0 -> 1
| n -> n * fact (n-1)
As you can see, there is a single parameter which is pattern matched with provided conditions.
It's called a pattern matching function and is described on MSDN: Match Expressions (F#)
Upvotes: 6