Closed jcubic closed 3 months ago
You mean simpler then the one that I've added? With just the single function?
Sure, will add one.
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))))
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)))))
@lassik you can add different solutions to the cookbook like we have with integer->list
.
Reverse recipe to
integer->list