fork(1) download
  1. ; nearest pair
  2.  
  3. (define (nearest-pair xs target)
  4. (let ((pos (list)))
  5. (do ((i 0 (+ i 1)) (ys xs (cdr ys))) ((null? ys))
  6. (set! pos (cons (cons (car ys) i) pos)))
  7. (let loop ((i 0) (xs xs) (np #f) (dist #e1e9))
  8. (if (null? xs) np
  9. (let ((j (assoc (- target (car xs)) pos)))
  10. (cond ((not j) (loop (+ i 1) (cdr xs) np dist))
  11. ((= i (cdr j)) (loop (+ i 1) (cdr xs) np dist))
  12. ((< (abs (- i (cdr j))) dist)
  13. (loop (+ i 1) (cdr xs) (cons (car xs) (car j)) (abs (- i (cdr j)))))
  14. (else (loop (+ i 1) (cdr xs) np dist))))))))
  15.  
  16. (display (nearest-pair '(1 5 3 6 4 2) 7)) (newline)
Success #stdin #stdout 0.03s 8344KB
stdin
Standard input is empty
stdout
(3 . 4)