schemedoc / cookbook

New Scheme Cookbook
https://cookbook.scheme.org
29 stars 3 forks source link

list->integer #72

Closed jcubic closed 3 months ago

jcubic commented 3 months ago

Reverse recipe to integer->list

jcubic commented 3 months ago

You mean simpler then the one that I've added? With just the single function?

Sure, will add one.

lassik commented 3 months ago

Adding digits is a textbook problem for a fold:

(define (list->integer digits)
  (let* ((minus? (eqv? '- (car digits)))
         (digits (if minus? (cdr digits) digits)))
    (* (if minus? -1 1)
       (fold (lambda (digit result) (+ digit (* 10 result)))
             0
             digits))))

Or use char lists:

(define (list->integer digits)
  (define (digit-char d) (integer->char (+ d (char->integer #\0))))
  (define (digit-or-minus-char d) (if (eqv? '- d) #\- (digit-char d)))
  (string->number (list->string (map digit-or-minus-char digits))))
lassik commented 3 months ago

This works out of the box in Gambit and Gauche:

(define (list->integer digits)
  (string->number
   (with-output-to-string (lambda () (for-each display digits)))))
jcubic commented 3 months ago

@lassik you can add different solutions to the cookbook like we have with integer->list.