Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

F# Recursion termination

Tags:

recursion

f#

I have been reading alot about functional programming and f#. I have a snippet of code that I cannot understand. I am familiar with recursive programs but this particular code is bugging me

open System

let rec fact x =
    if x < 1 then 1
    else x * fact (x - 1)

fact 6

In this snippet of code there is no where in the code that terminates the recusion. How does this program know when to stop. If I programmed this in c# I would tell the program to stop recursing when the index or iterator is higher then 6.

like image 901
Luke101 Avatar asked Sep 15 '26 16:09

Luke101


1 Answers

The recursion stops when it x is less than 1 because the result of the expression is then 1

if x < 1 then 1

In C# the function would look as follows:

public int fact(int x)
{
   if (x < 1)
      return 1;
   else
      return x * fact(x - 1);
}

Pure functional programming is interesting because there is never a return, all the program does is evaluate. You need to ask yourself 'What does this expression evaluate to?'

like image 93
linuxuser27 Avatar answered Sep 19 '26 05:09

linuxuser27



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!