What are the side effects of the performance of defining functions inside a recursive function vs outside in F #

If you have a recursive function that relies on some other function, what is the preferred way to implement it?

1) outside the recursive function

let doSomething n = ... let rec doSomethingElse x = match x with | yourDone -> ... | yourNotDone -> doSomethingElse (doSomething x) 

2) inside a recursive function

 let rec doSomethingElse x = let doSomething n = ... match x with | yourDone -> ... | yourNotDone -> doSomethingElse (doSomething x) 

3) encapsulate both inside the third function

 let doSomethingElse x = let doSomething n = ... let innerDoSomethingElse = match x with | yourDone -> ... | yourNotDone -> innerDoSomethingElse (doSomething x) 

4) is something even better?

+6
source share
1 answer
 module Test = let fx = let add ab = a + b //inner function add x 1 let f2 x = let add a = a + x //inner function with capture, ie, closure add x let outerAdd ab = a + b let f3 x = outerAdd x 1 

Translated to:

 [CompilationMapping(SourceConstructFlags.Module)] public static class Test { public static int f(int x) { FSharpFunc<int, FSharpFunc<int, int>> add = new add@4 (); return FSharpFunc<int, int>.InvokeFast<int>(add, x, 1); } public static int f2(int x) { FSharpFunc<int, int> add = new add@8-1 (x); return add.Invoke(x); } public static int f3(int x) { return outerAdd(x, 1); } [CompilationArgumentCounts(new int[] { 1, 1 })] public static int outerAdd(int a, int b) { return (a + b); } [Serializable] internal class add@4 : OptimizedClosures.FSharpFunc<int, int, int> { internal add@4 () { } public override int Invoke(int a, int b) { return (a + b); } } [Serializable] internal class add@8-1 : FSharpFunc<int, int> { public int x; internal add@8-1 (int x) { this.x = x; } public override int Invoke(int a) { return (a + this.x); } } } 

The only extra cost to the internal function - this new instance of FSharpFunc - seems insignificant.

If you are not very performance sensitive, I would go with the area that makes the most sense, i.e. the narrowest possible coverage.

+5
source

Source: https://habr.com/ru/post/900228/


All Articles