fork(3) download
  1. ; lunar arithmetic
  2.  
  3. (define (digits n . args)
  4. (let ((b (if (null? args) 10 (car args))))
  5. (let loop ((n n) (d '()))
  6. (if (zero? n) d
  7. (loop (quotient n b)
  8. (cons (modulo n b) d))))))
  9.  
  10. (define (undigits ds . args)
  11. (let ((b (if (null? args) 10 (car args))))
  12. (let loop ((ds ds) (n 0))
  13. (if (null? ds) n
  14. (loop (cdr ds) (+ (* n b) (car ds)))))))
  15.  
  16. (define (terran->lunar n) (reverse (digits n)))
  17. (define (lunar->terran xs) (undigits (reverse xs)))
  18.  
  19. (define (plus xs ys)
  20. (define (map0 f xs ys)
  21. (let loop ((xs xs) (ys ys) (zs (list)))
  22. (cond ((and (null? xs) (null? ys)) (reverse zs))
  23. ((null? xs) (loop xs (cdr ys) (cons (f 0 (car ys)) zs)))
  24. ((null? ys) (loop (cdr xs) ys (cons (f (car xs) 0) zs)))
  25. (else (loop (cdr xs) (cdr ys) (cons (f (car xs) (car ys)) zs))))))
  26. (map0 max xs ys))
  27.  
  28. (define (times xs ys)
  29. (define (times-one m xs)
  30. (map (lambda (x) (min m x)) xs))
  31. (let loop ((ys ys) (0s (list)) (zs (list)))
  32. (if (null? ys) zs
  33. (loop (cdr ys) (cons 0 0s)
  34. (plus (times-one (car ys) (append 0s xs)) zs)))))
  35.  
  36. (display (lunar->terran (plus (terran->lunar 357) (terran->lunar 64)))) (newline)
  37. (display (lunar->terran (times (terran->lunar 357) (terran->lunar 64)))) (newline)
Success #stdin #stdout 0s 50288KB
stdin
Standard input is empty
stdout
367
3564