ilength.scm 878 B

12345678910111213141516171819202122232425262728293031323334
  1. ; Copyright (c) 1993-2007 by Richard Kelsey and Jonathan Rees. See file COPYING.
  2. ; Integer-length, a la Common Lisp, written in portable Scheme.
  3. (define-syntax cons-stream
  4. (syntax-rules ()
  5. ((cons-stream head tail)
  6. (cons head (delay tail)))))
  7. (define head car)
  8. (define (tail s) (force (cdr s)))
  9. (define integer-length
  10. (let ()
  11. (define useful
  12. (let loop ((p 256) (n 4))
  13. (cons-stream (cons p n)
  14. (loop (* p p) (* n 2)))))
  15. (define (recur n)
  16. (if (< n 16)
  17. (vector-ref '#(0 1 2 2 3 3 3 3 4 4 4 4 4 4 4 4) n)
  18. (let loop ((s useful) (prev 16))
  19. (let ((z (head s)))
  20. (if (< n (car z))
  21. (+ (cdr z) (recur (quotient n prev)))
  22. (loop (tail s) (car z)))))))
  23. (define (integer-length n)
  24. (if (exact? n)
  25. (if (< n 0)
  26. (recur (- -1 n))
  27. (recur n))
  28. (integer-length (inexact->exact n))))
  29. integer-length))