(define wadd (lambda (i L)
(if (null? L) 0
(+ i (car L)))
(set! i (+ i (car L)))
(set! L (cdr L))))
(wadd 9 '(1 2 3))
This returns nothing. I expect it to do (3 + (2 + (9 + 1)), which should equate to 15. Am I using set! the wrong way? Can I not call set! within an if condition?
I infer from your code that you intended to somehow traverse the list, but there’s nothing in the
waddprocedure that iterates over the list – no recursive call, no looping instruction, nothing: just a misused conditional and a couple ofset!s that only get executed once. I won’t try to fix the procedure in the question, is beyond repair – I’d rather show you the correct way to solve the problem. You want something along these lines:When executed, the previous procedure will evaluate this expression:
(wadd 9 '(1 2 3))like this:(+ 3 (+ 2 (+ 1 9))). Notice that, as pointed by @Maxwell, the above operation can be expressed more concisely using foldl:As a general rule, in Scheme you won’t use assignments (the
set!instruction) as frequently as you would in an imperative, C-like language – a functional-programming style is preferred, which relies heavily on recursion and operations that don’t mutate state.