【问题标题】:F#: Mutually recursive functions [duplicate]F#:相互递归函数[重复]
【发布时间】:2010-09-01 18:30:30
【问题描述】:

可能重复:
[F#] How to have two methods calling each other?

大家好,

我有一个场景,我有两个函数可以从相互递归中受益,但我不确定如何在 F# 中执行此操作

我的场景并不像下面的代码那么简单,但是我想得到类似compile的东西:

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

【问题讨论】:

标签: f# recursion mutual-recursion


【解决方案1】:

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

【讨论】:

  • 比我快 42 秒... :-)
  • +1,很好,没有意识到您可以将and 与 let 绑定一起使用。我认为它的使用仅限于type 声明。
  • 如果您有相互递归的类型(如两个 DU)和两个将每个作为输入参数的函数,它会特别有用(必要)。
【解决方案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

【讨论】:

    【解决方案3】:

    使用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
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2016-06-13
      • 1970-01-01
      • 1970-01-01
      • 2017-06-19
      • 1970-01-01
      • 1970-01-01
      • 2022-01-03
      • 2015-04-10
      相关资源
      最近更新 更多