Reputation: 41
I am very new to F# programming. I am looking for an answer as to why the following recursive function will exit when the n=0 condition is reached. Does the "then 1" syntax have a special meaning that equates to EXIT?
let rec factorial n =
if n = 0
then 1
else n * factorial (n - 1)
Upvotes: 4
Views: 480
Reputation: 10624
Functional programming languages are expression oriented, as opposed to statement oriented. This means that everything is an expression that can be evaluated into a value.
The control flow structures, if
and match
, are also just expressions. The compiler checks that all branches of these expressions return the same type.
If you're familiar with the conditional ternary operator in other languages, F#'s expression if true then 1 else 0
, is equivalent to true ? 1 : 0
.
Furthermore, the function doesn't "exit" as such. It completes evaluation. Each instance of the function (there will be n + 1
instances) completes evaluation at the end of the if
/then
/else
expression.
Upvotes: 6