fork download
  1. ; extract number from string
  2.  
  3. (define (extract-number str)
  4. (let loop ((cs (string->list str)) (prev #\X) (n 0))
  5. (cond ((null? cs)
  6. (* (if (char=? prev #\-) -1 1) n))
  7. ((char-numeric? (car cs))
  8. (loop (cdr cs) prev
  9. (+ (* n 10)
  10. (- (char->integer (car cs))
  11. (char->integer #\0)))))
  12. ((positive? n)
  13. (* (if (char=? prev #\-) -1 1) n))
  14. (else (loop (cdr cs) (car cs) n)))))
  15.  
  16. (display (extract-number "-123")) (newline)
  17. (display (extract-number "-123junk")) (newline)
  18. (display (extract-number "junk-123")) (newline)
  19. (display (extract-number "junk-123junk")) (newline)
  20. (display (extract-number "junk-123junk456")) (newline)
  21. (display (extract-number "junk123junk456")) (newline)
Success #stdin #stdout 0.01s 50288KB
stdin
Standard input is empty
stdout
-123
-123
-123
-123
-123
123