odd-n-to-0

mail@pastecode.io avatar
unknown
scheme
3 years ago
2.1 kB
7
Indexable
Never
;; odd-from-n-starter.rkt

;  PROBLEM:
;  
;  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.
;  


;; Includes
(require 2htdp/image)

;; Constants
(define FONT-SIZE 20)
(define FONT-COLOR "black")


;; Data Definition

;; Natural is one of:
;; - 0 (cons 0 empty)
;; - (cons Natural ListOfNatural)
;; interp a list of Naturals


(define LON-1 (cons 0 empty))
(define LON-2 (cons 1 (cons 0 empty)))
(define LON-3 (cons 3 (cons 2 (cons 1 (cons 0 empty)))))

#;
(define (func-for-lon lon)
  (cond [(zero?)  (...)]    ; Base case
        [else (... (first lon)                      ; Natural 
                   (func-for-lon (rest lon)))]))    ; Natural Recursion
;;  Combination
;; Template rules used:
;; - one of 2 cases:
;; - Base Compound:   (cons 0 empty)
;; - Compound: (cons Natural ListOfNatural)
;; - Self-reference: (rest los) is ListOfNatural

;; Functions
;; Natural -> ListOfNatural
;; Takes a number and makes a list from that number down to 0
(check-expect (list-n-to-0 0) (cons 0 empty))
(check-expect (list-n-to-0 3) (cons 3 (cons 2 (cons 1 (cons 0 empty)))))
              
;(define (list-n-to-0 n) ...) ;stub

(define (list-n-to-0 n)
  (cond [(zero? n)  (cons 0 empty)]    ; Base case
        [else (cons n                     ; Natural 
                   (list-n-to-0 (sub1 n)))]))    ; Natural Recursion

;; ListOfNatural -> ListOfNatural
;; Takes a list n-to-0 and returns odd-n-to-0
(check-expect (odd-n-to-0 LON-1) empty)
(check-expect (odd-n-to-0 LON-2) (cons 1 empty))
(check-expect (odd-n-to-0 LON-3) (cons 3 (cons 1 empty)))

;(define (odd-n-to-0 lon) ...) ;stub

(define (odd-n-to-0 lon)
  (cond [(zero? (first lon))  empty]    ; Base case
        [else
         (cons (if (odd? (first lon))
                (first lon)                     ; Natural 
                   (odd-n-to-0 (rest lon)))
               (odd-n-to-0 (rest lon)))]))    ; Natural Recursion