【问题标题】:How to add elements to a list on a recursive function that doesn't pass that list as an argument?如何将元素添加到不将该列表作为参数传递的递归函数的列表中?
【发布时间】:2014-05-18 06:58:44
【问题描述】:

标题说了很多,这就是功能:

optimistic: dtree -> int * (int list)

let rec optimistic dt =
  match dt with
  | Decision(choiceL, costL, l, choiceR, costR, r) -> 
    if costL > costR then 0::xs; optimistic r - costR
    else 1::xs ; optimistic l - costL 
  | Chance(eventL, probL, l, eventR, probR, r) ->
    if optimistic l > optimistic r then 0::xs ; optimistic l
    else 1::xs ; optimistic r
  | Outcome -> value, x
;;

基本上,根据我们取下二叉树的“路线”,我们将通过使用 0(左转时)或 1(右转时)记录该路径并将这些数字一起组成一个列表,我们将在最后返回。

问题是,我想不出一种方法让这个列表通过递归持续存在,因为它没有被当作参数。任何想法如何做这样的事情?

【问题讨论】:

    标签: list recursion tree ocaml binary-tree


    【解决方案1】:

    我认为简短的回答是您应该有一个 将列表作为参数的辅助函数。

    如果您坚持使用命令式技术,您可以在更全局的范围内拥有一个可变列表值,该值在您遍历树时会被修改。 (即便如此,最好有一个辅助函数来避免将可修改列表放入最外层范围。)

    【讨论】:

      【解决方案2】:

      您应该将列表作为参数,但如果您不关心尾调用优化,您可以这样写:

      let rec optimistic dt =
        match dt with
        | Decision(choiceL, costL, l, choiceR, costR, r) -> 
          if costL > costR then
            let c, t = optimistic r in
            c - costR, 0 :: t
          else
            let c, t = optimistic l in
            c - costL, 1 :: t
        | Chance(eventL, probL, l, eventR, probR, r) ->
          let cR, tR = optimistic r in
          let cL, tL = optimistic l in
          if cL > cR then
            cL, 0 :: tL
          else
            cR, 1 :: tR
        | Outcome -> 0, []
      ;;
      

      【讨论】:

        猜你喜欢
        • 2022-01-02
        • 1970-01-01
        • 2021-10-17
        • 2012-10-26
        • 1970-01-01
        • 2011-02-14
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多