Creating local functions in F #

For example, I have two additive functions:

module Add

let add2 a =
    let innerFn a = a + 2
    innerFn a
let add2' a =
    let innerFn' () = a + 2
    innerFn' ()

let res1 = add2 0
let res2 = add2' 1

From what I know, both innerFnwill be compiled into FSharpFunc<int,int>and FSharpFunc<unit,int>respectively and will be initialized every time add2or is called add2'.

How can I rewrite code to convert them to static local functions of a static class (without initializing FSharpFunc), as in C # 7?

+4
source share
1 answer

You probably don't need to worry about that. In the Debug assembly, each local function becomes a delegate. In the Release assembly, functions are either built-in or become static methods in a static class.

By creating and decompiling the question code in the Debug assembly, you will get:

public static int add2(int a)
{
    return 5 + (new Program.innerFn@5()).Invoke(a);
}

public static int add2'(int a)
{
    return (new Program.innerFn'@8(a)).Invoke(null);
}

.

Release, , :

public static int add2(int a)
{
    return a + 2;
}

public static int add2'(int a)
{
    return a + 2;
}

.

, add2 :

let add2 a =
    let innerFn a = if a < 3 then a+1 else a + 2
    5 + innerFn a
let add2' a =
    let innerFn' () = a + 2
    innerFn' () 

Release :

public static int add2(int a)
{
    return 5 + Program.innerFn@5(a);
}

public static int add2'(int a)
{
    return a + 2;
}

internal static int innerFn@5(int a)
{
    if (a < 3)
    {
        return a + 1;
    }
    return a + 2;
}
+7

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


All Articles