Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Nested functions in F#

Tags:

function

f#

I have a simple function that lists every prime factor of a given input number. It is composed by:

let rec f n x a = 
    if x = n then
        x::a
    elif n % x = 0 then 
        f (n/x) x (x::a)
    else
        f n (x+1) a

let fact n = f n 2 []

fact 315
val factors : int list = [7; 5; 3; 3]

It works, but I would like to make of it a single function: how can I define fact with f directly nested in? I tried to apply the concept brilliantly expressed here, but I fail to abstract how to nest a three argument function (f) in a one arguments one (fact).

like image 291
Worice Avatar asked Jun 28 '26 05:06

Worice


1 Answers

  1. Move the function body of fact to a new line. Make sure that it's indented.
  2. Add a blank line between the declaration of fact and the function body you just moved.
  3. Cut the entire definition of fun, and paste it into the blank line you created in the second step.
  4. Indent the copied code so that it become a local function of fact.
like image 59
Mark Seemann Avatar answered Jun 30 '26 03:06

Mark Seemann