首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >在递归函数内部定义函数与在F#外部定义函数有什么性能副作用

在递归函数内部定义函数与在F#外部定义函数有什么性能副作用
EN

Stack Overflow用户
提问于 2011-10-28 02:00:40
回答 1查看 277关注 0票数 6

如果你有一个依赖于其他函数的递归函数,那么实现它的首选方法是什么?

1)在递归函数外部

代码语言:javascript
复制
let doSomething n = ...
let rec doSomethingElse x =
    match x with
    | yourDone -> ...
    | yourNotDone -> doSomethingElse (doSomething x)

2)在递归函数内部

代码语言:javascript
复制
let rec doSomethingElse x =
    let doSomething n = ...
    match x with
    | yourDone -> ...
    | yourNotDone -> doSomethingElse (doSomething x)

3)将两者封装在第三个函数中

代码语言:javascript
复制
let doSomethingElse x =
    let doSomething n = ...
    let innerDoSomethingElse =
        match x with
        | yourDone -> ...
        | yourNotDone -> innerDoSomethingElse (doSomething x)

4)有更好的东西吗?

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2011-10-28 02:15:17

代码语言:javascript
复制
module Test =

    let f x = 
      let add a b = a + b //inner function
      add x 1

    let f2 x =
      let add a = a + x //inner function with capture, i.e., closure
      add x

    let outerAdd a b = a + b

    let f3 x =
      outerAdd x 1

翻译为:

代码语言:javascript
复制
[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);
        }
    }
}

内部函数唯一的额外开销是创建一个新的FSharpFunc实例--看起来可以忽略不计。

除非你对性能非常敏感,否则我会选择最有意义的作用域,也就是说,最窄的作用域。

票数 5
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/7920234

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档