; ladder range

(define left '(0 1 4 9 16 25 36 49 64 81 100))
(define right '(0 3 14 15 23 24 25 49 57 92 100))

(define slopes
  (map (lambda (left right) (- right left))
       left right))
       
(define intercepts left)

(display slopes) (newline)
(display intercepts) (newline)

(define (lt? idx x y)
  (let ((slope (list-ref slopes idx))
        (intercept (list-ref intercepts idx)))
    (positive? (- (+ (* slope x) intercept) y))))

(display (lt? 7 0.5 50)) (newline)
(display (lt? 8 0.5 50)) (newline)

(define (ladder x y)
  (when (or (lt? 0 x y) (not (lt? 10 x y)))
    (error 'ladder "out of bounds"))
  (let loop ((lo 0) (hi (- (length left) 1)))
    (let ((mid (quotient (+ lo hi) 2)))
      (cond ((= (- hi lo) 1) (values lo hi))
            ((lt? mid x y) (loop lo mid))
            (else (loop mid hi))))))

(call-with-values
  (lambda () (ladder 0.5 50))
  (lambda (lo hi)
    (display lo) (newline)
    (display hi) (newline)))

(call-with-values
  (lambda () (ladder 0.25 25))
  (lambda (lo hi)
    (display lo) (newline)
    (display hi) (newline)))