;; The first three lines of this file were inserted by DrRacket. They record metadata
;; about the language level of this file in a form that our tools can easily process.
#reader(lib "htdp-intermediate-lambda-reader.ss" "lang")((modname curve) (read-case-sensitive #t) (teachpacks ()) (htdp-settings #(#t constructor repeating-decimal #f #t none #f () #f)))
; A CurveTree is one of:
; - (make-segment Posn Posn)
; - (make-connect CurveTree CurveTree)
(define-struct segment [p1 p2])
(define-struct connect [c1 c2])
; dist : Number Number Number Number -> Number
; distance between two cartesian points
(define (dist x1 y1 x2 y2)
(sqrt (+ (sqr (- x1 x2)) (sqr (- y1 y2)))))
; generate-curve-tree : [Number -> Number] Number Number -> CurveTree
; subdivide the given function between the bounds
; termination: by dividing the interval in half, the points keep getting
; closer, as long as the function is continous
(define (generate-curve-tree f x1 x2)
(cond [(< (dist x1 (f x1) x2 (f x2)) 0.1)
(make-segment (make-posn x1 (f x1))
(make-posn x2 (f x2)))]
[else (make-connect (generate-curve-tree f x1 (+ x1 (/ (- x2 x1) 2)))
(generate-curve-tree f (+ x1 (/ (- x2 x1) 2)) x2))]))
; curve-tree-length : CurveTree -> Number
; compute the length of all the segments
(define (curve-tree-length c)
(cond [(segment? c) (dist (posn-x (segment-p1 c)) (posn-y (segment-p1 c))
(posn-x (segment-p2 c)) (posn-y (segment-p2 c)))]
[else (+ (curve-tree-length (connect-c1 c))
(curve-tree-length (connect-c2 c)))]))
(check-within (curve-tree-length
(make-segment (make-posn 0 0) (make-posn 5 5)))
(dist 0 0 5 5)
0.1)
(check-within (curve-tree-length
(make-connect
(make-segment (make-posn 0 0) (make-posn 5 5))
(make-segment (make-posn 5 5) (make-posn 5 6))))
(+ (dist 0 0 5 5)
(dist 5 5 5 6))
0.1)
(curve-tree-length (generate-curve-tree (λ (x) 1) -5 5))
; f : Number -> Number
; draw a quarter-circle
(define (f x) (sqrt (- (sqr 500) (sqr x))))