2

第 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))

我认为这同样正确。

; 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))
4

1 回答 1

6

两种形式都是正确的并且完全等效,这只是风格问题。尽管可以说这更清楚一点,因为它明确地返回了什么:

(if (empty? lst)
  empty
  ...)

最后,这是个人品味与编码约定的问题。如果你是一个团队的成员并且每个人都在使用第一种形式,那么你应该使用它。另一方面,如果你是一个孤独的程序员,那么使用更适合你口味的形式。

于 2013-03-03T22:52:17.533 回答