On Tue, Mar 11, 2014 at 03:30:56PM +0100, Daniel Carrera wrote:
> Hello,
> 
> I'm having a problem with (fold):
> 
> 
> (use srfi-1)  ; List library.
> 
> (fold (lambda (a b) (+ (* a 10) b)) 0 '(1 2 3))
> 
> I was expecting this to return 123, but it returns 60. I'm confused. In my
> mind, at each step I shift the current value to the left (i.e. multiply by
> 10) and add the new digit. So the steps should be:
> 
> 1 , 2 --> 10 + 1 = 12
> 12 , 3 --> 120 + 3 = 123
> 
> What am I missing?

You need to multiply the "memo" by 10, not the item:

#;1> (use srfi-1)
#;2> (fold (lambda (a b) (print `(+ (* ,a 10) ,b)) (+ (* a 10) b)) 0 '(1 2 3))
(+ (* 1 10) 0)
(+ (* 2 10) 10)
(+ (* 3 10) 30)
60
#;3> (fold (lambda (a b) (+ (* b 10) a)) 0 '(1 2 3))
123

To avoid such mistakes, it's helpful to use mnemonic names:

(fold (lambda (item result) (+ (* result 10) item)) 0 '(1 2 3))

Cheers,
Peter
-- 
http://www.more-magic.net

_______________________________________________
Chicken-users mailing list
Chicken-users@nongnu.org
https://lists.nongnu.org/mailman/listinfo/chicken-users

Reply via email to