5a: Naturals / Practice Problems 2

May 20, 2021 00:00 ·

問題文 🔗

 Design a function called odd-from-n that consumes a natural number n, and produces a list of all
 the odd numbers from n down to 1.

 Note that there is a primitive function, odd?, that produces true if a natural number is odd.

問題文のリンク はこちら。

解答 🔗

;; Number -> ListOfNatural
;; produces a list of the odd numbers from n down to 1
;; (define (odd-from-n n) (cons 1 empty)) ; stub
(check-expect (odd-from-n 0) empty)
(check-expect (odd-from-n 2) (cons 1 empty))
(check-expect (odd-from-n 3) (cons 3 (cons 1 empty)))

(define (odd-from-n n)
  (cond
        [(= n 0) empty]
        [(= n 1) (cons 1 empty)]
        [(odd? n) (cons n (odd-from-n (sub1 n)))]
        [else (odd-from-n (sub1 n))]))

メモ 🔗

  • odd? で奇数かどうかを判定できる