I need a function that will take in a list of characters and numbers, and then return the numbers added up (ignoring the characters). This is what I have so far:
(define (adder lst)
(cond
((null? lst)
0)
((number? (car lst))
(+(adder (car lst)) (adder (cdr lst))))
((char? (car lst))
((adder(cdr lst))))
))
(display (adder '(asd12sdf)))
Running it on codepad.org just displays void. I know the code is wrong because it looks wrong, but I have no idea how to fix it… How do I have the function keep track of the first number it finds and add it to the next one it finds, while skipping all characters?
In your second cond case, there’s no reason to run
adderon(car lst). Just adding(car list)itself to the recursive step should work.For the last line, don’t test
(char? (car lst)). Just make the last line theelseclause, meaning that anything BUT a number will go to the else line.The reason you’re getting void is because your input doesn’t satisfy any of the
condconditions, and you have noelse, so the answer is nothing (i.e.(void)).The last mistake is in the input you’re giving it.
'(asd12sdf)is literally a list with one symbol named “asd12sdf”. I think you want to give it'(a s d 1 2 s d f)(a list of 6 symbols and 2 numbers) which should result in 3. Notice that there’s a very important difference between the symbol'aand the character#\a.It looks like you have the logic down, so your problem doesn’t seem to be functional languages, just Scheme’s syntax.
Edit: and in the last line, you have
((adder(cdr lst)))which has one too many parens wrapped around it. That will cause Scheme to attempt to evaluate the result of adder (which is a number) as a procedure (error!).