记录类型的递归成员函数和"rec"函数.关键词 [英] Record-type recursive member functions and the "rec" keyword

查看:96
本文介绍了记录类型的递归成员函数和"rec"函数.关键词的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我一直认为,在F#中,我们需要为每个递归函数使用rec关键字,例如:

I've always believed that in F# we needed to use the rec keyword for every recursive function, for example:

let rec factorial = function
| 0 -> 1
| k when k > 0 ->  k * (factorial (k - 1))
| failwith "oops!"

今天我在玩F#,并且想出了类似于以下代码:

Today I was playing around with F# and I came up with a code similar to the following:

let MyRecordType =
    { Something     : float;
      SomethingElse : int }
    with
        static member factorial = function
            | 0 -> 1
            | k when k > 0 ->  k * (MyRecordType.factorial (k - 1))
            | failwith "oops!"

如您所见,我刚刚定义了一个递归函数,但最初我犯了一个错误:我忘记了通过rec关键字将函数声明为 recursive

As you see, I've just defined a recursive function, but I made what at first seemed like a mistake: I forgot to declare the function as recursive by means of the rec keyword.

但是令我惊讶的是它编译!还有更多的功能:如果添加rec关键字,那么这是语法错误!

But to my surprise it compiles! And there's more to it: if you add the rec keyword, then it is a syntax error!

type MyRecordType =
    { (* ... *) }
    with
        // syntax error:
        static member rec factorial = function
        (* ... *)

我在Google上四处寻找解释,但一无所获.在MSDN文档中,我找不到rec关键字的任何提及" rel ="noreferrer">有关递归函数的页面,截止到2010年1月3日,它没有提及我要问的情况.

I've googled around for an explanation but got nothing. In the MSDN documentation, I couldn't find any mention to the rec keyword outside the page about recursive functions, and as of 2010-01-03 it does not mention the case I'm asking about.

非静态成员也会发生同样的事情.

Exactly the same thing happens with non-static members.

那么,为什么在记录类型的成员函数上使用rec关键字会导致语法错误?

So, why is it a syntax error to use the rec keyword on member functions of a record-type?

推荐答案

'let rec'并不是要定义递归函数,而是要在环境中定义一个绑定,其中包括当前的绑定. 要绑定的变量.您也可以使用'let rec'来定义例如无限列表.通常,您不希望包含绑定 在环境中,您可能想使用相同的名称访问一个更早的变量.

'let rec' isn't about defining recursive functions, but defining a binding in an environment, that includes the binding for the current variable to be bound. You could use 'let rec' just as well to define e.g. an infinite list. Often, you don't want the binding to be included in the environment, as you might want to access an earlier variable by the same name.

在定义静态成员函数factorial时,您不是在寻找变量"factorial"的绑定,而是在寻找类型的绑定. "MyRecordType"(在环境中作为类型定义),如果碰巧有一个称为"factorial"的静态成员函数, 它有.

When you are defining the static member function, factorial, you aren't looking for a binding for a variable 'factorial', but for a type 'MyRecordType' (which is in the environment as a type definition), and if it happens to have a static member function called 'factorial', which it has.

这篇关于记录类型的递归成员函数和"rec"函数.关键词的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆