生成和结构递归有什么区别?

时间:2017-11-23 05:17:42

标签: recursion functional-programming scheme racket

Racket中的生成和结构递归有什么区别?

1 个答案:

答案 0 :(得分:2)

当“子问题”与可能的数据部分完全匹配时,就会发生结构递归。

例如,处理列表lox。琐碎的情况是lox为空。否则,第一个子问题是处理(first lox),第二个子问题是处理(rest lox)。您可以通过调用辅助函数来解决每个子问题,然后组合解决方案。

(define (process-list-of-x lox)
  (cond
    ;; trivial case
    [(empty? lox) ...]
    [(cons? lox)
     ; combine the solutions
     (...
      ; solve the first sub-problem
      (process-x (first lox))         ; data-def tells you what the first sub-problem is
      ...
      ; solve the second sub-problem
      (process-list-of-x (rest lox))  ; data-def tells you what the second sub-problem is
      ...)]))

有什么不同的是,结构递归告诉你子问题是什么,在生成递归中,子问题可能是什么。你经常需要一个新的想法来分解它。特有问题的尤里卡时刻,而不是数据。

(define (solve-problem prob)
  (cond
    ;; trivial case
    [(trival-problem? prob) (... prob ...)]
    [else
     ; combine the solutions
     (...
      ; solve the first sub-problem
      (solve-problem (generate-first-sub-problem prob))   ; you have to figure this out
      ...
      ; solve the second sub-problem
      (solve-problem (generate-second-sub-problem prob))  ; data-def doesn't tell you how
      ...)]))

此外,结构递归保证它终止,因为子问题来自分解数据。在生成递归中,子问题可能更复杂,因此您需要一些其他方法来确定它是否会终止。