2010-09-01 101 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