可能的重复:
f#]如何让两种方法互相呼叫?

大家好,

我有一个场景,我有两个功能可以从相互递归中受益,但我不确定如何在F#中做到这一点

我的情况不像以下代码那样简单,但是我想得到类似的编译:

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
有帮助吗?

解决方案

您也可以使用 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

其他提示

要获得相互递归的函数,只需将一个作为参数传递给另一个功能

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

使用 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
许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top