为什么返回空而不是列表本身?

dot*_*00b 2 scheme racket

第4章,HtDP.

注意:我也在其他问题中看到了这一点.

是出于清晰的原因还是算法的原因,我不知道,基本情况返回空而不是列表本身是空的.

例:

; List-of-numbers -> List-of-numbers
; compute the weekly wages for all given weekly hours
(define (wage* alon)
  (cond
    [(empty? alon) empty] ;<---- see here
    [else (cons (wage (first alon)) (wage* (rest alon)))]))

; Number -> Number
; compute the wage for h hours of work
(define (wage h)
  (* 12 h))
Run Code Online (Sandbox Code Playgroud)

我认为这是正确的.

; List-of-numbers -> List-of-numbers
; compute the weekly wages for all given weekly hours
(define (wage* alon)
  (cond
    [(empty? alon) alon] ;<---- see here
    [else (cons (wage (first alon)) (wage* (rest alon)))]))

; Number -> Number
; compute the wage for h hours of work
(define (wage h)
  (* 12 h))
Run Code Online (Sandbox Code Playgroud)

Ósc*_*pez 6

两种形式都是正确的,完全相同,只是风格问题.虽然可以说这有点清楚,因为它明确地返回了什么:

(if (empty? lst)
  empty
  ...)
Run Code Online (Sandbox Code Playgroud)

最后,这是个人品味与编码惯例的问题.如果您是团队成员并且每个人都在使用第一个表单,那么您应该使用它.另一方面,如果你是一个单独的程序员,那么使用更适合你口味的表格.