简体   繁体   English

在F#中创建本地函数

[英]Create local functions in F#

For example, I have 2 additive functions: 例如,我有2个附加功能:

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 known, both innerFn s will be compiled to FSharpFunc<int,int> and FSharpFunc<unit,int> respectively, and will be initialized everytime the add2 or add2' is called. 根据我所知,两个innerFn将分别编译为FSharpFunc<int,int>FSharpFunc<unit,int> ,并且每次调用add2add2'都会初始化。

How can I rewrite the code to transform them to static local functions of the static class (thus no FSharpFunc initialization), like in C# 7? 如何重写代码以将它们转换为静态类的静态本地函数(因此没有FSharpFunc初始化),就像在C#7中一样?

You probably don't have to worry about this. 你可能不必担心这个。 In a Debug build, every local function becomes a delegate. 在Debug构建中,每个本地函数都成为委托。 In a Release build, the functions are either inlined or do become static methods in the static class. 在发布版本中,函数被内联还是成为静态类的静态方法。

By building and decompiling the question's code in a Debug build, you get : 通过在Debug构建中构建和反编译问题的代码,您将获得:

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);
}

Which does show a delegate initialization each time. 每次都会显示委托初始化。

In Release though, this becomes : 在Release中,这变为:

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

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

The functions were inlined and no delegate was generated. 这些函数是内联的,没有生成任何委托。

To avoid indlining, I made add2 a bit more complex : 为了避免陷入困境,我使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' () 

In this case, the Release build generated a static method in the class : 在这种情况下,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;
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM