[plt-scheme] help.... Me :)
(require (lib "testing.ss" "htdp"))
(define-struct interval (left right))
;; Interval = (make-interval L R) with L, R in Integer and R >= L
;; meaning: (make-interval L R) = (L,R]
;; (I sure wonder who chose this meaning.)
#|
Sample
r1 : 0 to 20
r2 : 2001 to 2008
|#
(define r1 (make-interval 0 20))
(define r2 (make-interval 2001 2008))
;; " my problem is to set operation intervals "
;; interval-length : Interval -> Nat
;; ( interval – length r2 ) --> 7
(define (interval-length r) (- (interval-right r) (interval-left r)))
(check-expect (interval-length r2) 7)
;; interval-print-all : Interval -> [Listof Integer]
;; (Interval-print- all r2 ) --> 2002 2003 2004 2005 2006 2007 2008
(define (interval-print-all r)
(local ((define L (interval-left r)))
(build-list (interval-length r) (lambda (i) (+ L i 1)))))
(check-expect (interval-print-all r2) (list 2002 2003 2004 2005 2006
2007 2008))
;; interval-combine : Interval Interval -> Interval
;; again, I sure wonder who'd ever assign such a silly problem
(define (interval-combine i1 i2)
(make-interval (min (interval-left i1) (interval-left i2))
(max (interval-right i1) (interval-right i2))))
(check-expect (interval-combine r1 r2) (make-interval 0 2008))
(check-expect (interval-combine r2 r1) (make-interval 0 2008))
;; interval-sum : Interval -> Integer
;; returns the sum of all elements
(define (interval-sum i)
(apply + (interval-print-all i)))
(check-expect (interval-sum (make-interval 1 3)) 5)
;; interval-mid : Interval -> Integer
;; the middle number in interval. If length is even, return the lower
mid
(define (interval-mid r1)
(quotient (+ (interval-right r1) (interval-left r1)) 2))
(check-expect (interval-mid r1) 10)
(check-expect (interval-mid r2) 2004)
;; interval-print-n : Interval Nat -> [Listof Integer]
;; prints first n elements of r1 ( less if length is lesser than n )
(define (interval-print-n r1 n)
(local ((define (take l n)
(cond
[(empty? l) empty]
[(zero? n) empty]
[else (cons (first l) (take (rest l) (sub1 n)))])))
(take (interval-print-all r1) n)))
(check-expect (interval-print-n r1 3) (list 1 2 3))
(check-expect (interval-print-n r1 10000) (interval-print-all r1))
(generate-report)