2010-09-01 102 views
11

可能重复:
[F#] How to have two methods calling each other?F#:相互递归函数

您好所有,

我遇到的情况,我会被相互递归利二便功能,但我真的不知道如何在F#中执行此操作。#

我的场景是n加时赛如下面的代码一样简单,但我希望得到类似的东西来编译:

let rec f x = 
    if x>0 then 
    g (x-1) 
    else 
    x 

let rec g x = 
    if x>0 then 
    f (x-1) 
    else 
    x 
+0

参见http://stackoverflow.com/questions/1378575/f-forward-type-declarations – Brian 2010-09-01 20:46:00

+0

我毫不犹豫地纪念这个作为一个重复,因为标题可能会更好... – Benjol 2010-09-02 05:03:10

+0

@Benjol:一般来说,我们不会删除重复的标题,但为了提高可搜索性,我们仍然关闭它们。 – dmckee 2010-09-03 17:31:25

回答

22

你可以还使用letrec ... and形式:

let rec f x = 
    if x>0 then 
    g (x-1) 
    else 
    x 

and g x = 
    if x>0 then 
    f (x-1) 
    else 
    x 
+1

打我42秒... :-) – 2010-09-01 18:56:06

+1

+1,尼斯,没有意识到你可以使用'和'与绑定。我认为它的使用仅限于'type'声明。 – JaredPar 2010-09-01 19:02:52

+0

如果你有相互递归的类型(比如两个DU)和两个把每个作为输入参数的函数,那么它是特别有用的(必要的)。 – Stringer 2010-09-01 19:11:09

2

为了得到相互递归函数只是一个传递到另一个作为参数

let rec f g x = 
    if x>0 then 
    g (x-1) 
    else 
    x 

let rec g x = 
    if x>0 then 
    f g (x-1) 
    else 
    x 
2

使用let rec ... and ...结构:

let rec f x = 
    if x>0 then 
    g (x-1) 
    else 
    x 

and g x = 
    if x>0 then 
    f (x-1) 
    else 
    x