Adding numbers from a list (e.g. asdf125dkf will return 8)

I need a function that will take a list of characters and numbers, and then return the numbers added (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 on codepad.org just displays void. I know that the code is wrong, because it looks wrong, but I have no idea how to fix it ... How do I function to track the first number found and add it to the next found, and skip all the characters?

+4
source share
3 answers

In your second case, there is no reason to run adder on (car lst) . Just adding (car list) to the recursive step should work.

For the last line, do not test (char? (car lst)) . Just make the last line in the else clause, which means something, BUT the number will go to another line.

The reason you get emptiness is because your input does not satisfy any of the cond conditions and you have no else , so the answer is nothing (i.e. (void) ).

The final mistake is what you give. '(asd12sdf) is literally a list with the symbol one named "asd12sdf". I think you want to give it '(asd 1 2 sdf) (a list of 6 characters and 2 numbers), which should lead to 3. Note that there is a very important difference between the character 'a and the character #\a .

It looks like you have logic, so your problem is not a functional language, just a schema syntax.

Edit: and in the last line you have ((adder(cdr lst))) that has too many partners wrapped around it. This will make Scheme try to evaluate the result of the adder (which is a number) as a procedure (error!).

+3
source

You should notice that this function is greater or less than sum , which can be defined simply with fold .

 (define (adder lst) (fold + 0 lst)) 

What does a fold do? In principle, it is defined as follows:

 (define (fold f initial lst) (if (null? lst) initial (fold f (f (car lst) initial) (cdr lst)))) 

(In other words, it calls the function f, a function of two arguments, for each element of lst, using the car lst as the first argument, and the accumulated result as the second argument for f.)

The problem you need to handle is that + does not know how to work with non-numeric values. No problem, you have already dealt with it. What happens if a symbol appears instead? Well, you are not adding anything to the overall value, so replace it with 0. Therefore, your solution is as simple as:

 (define (adder lst) (fold your-new-protected-+ 0 lst)) 
0
source

In general, Lisp:

 (reduce #'+ '(1 #\a #\b 2 1 2 #\c #\d 4) :key (lambda (item) (if (numberp item) item 0))) 

or

 (loop for item in '(1 #\a #\b 2 1 2 #\c #\d 4) when (numberp item) sum item) 
0
source

All Articles