like convert (1 2 3 4) to 1234~
+1
A:
This sounds like a homework question...
Think about powers of ten and what each digit in a number like 1234 actually means.
Aaron
2009-11-05 20:52:12
+1
A:
I write the code as following~~~it works, but the code may be too long~~~
(define (power b e)
(define (power-product a b e)
(if (= e 0)
a
(power-product (* a b ) b (- e 1))))
(power-product 1 b e))
(define (length items)
(if (null? items)
0
(+ 1 (length (cdr items)))))
(define (list->num lst)
(if (null? lst)
0
( + (* (power 10 (- (length lst) 1)) (car lst)) (list->num (cdr lst)))))
`length` and `power` are already defined in Scheme, although `expt` is the name of the latter.
Nathan Sanders
2009-11-06 07:14:07
+1
A:
Since you've posted your working solution, I'll post this. If you can't use let, you can do similar with a helper function.
(define (list->num l)
(let loop ((n 0) (l l))
(if (empty? l)
n
(loop (+ (* 10 n) (car l)) (cdr l)))))
A book like "The Little Schemer" is inexpensive, easy and fun to read, and it really gets you thinking in "Scheme mode". It will help you write more concise solutions.
z5h
2009-11-06 17:06:37
+2
A:
The problem is characterized by coalescing a list into a single value, strongly suggesting use of a fold:
(define (fold-left op initial items) (define (loop result rest) (if (null? rest) result (loop (op result (car rest)) (cdr rest)))) (loop initial items)) (define (list->num list) (fold-left (lambda (value digit) (+ (* value 10) digit)) 0 list)) (list->num '(1 2 3 4)) ;Value: 1234
Cirno de Bergerac
2009-11-24 10:55:08