开发者

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

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 adder on (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 the else clause, 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 cond conditions, and you have no else, 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 'a and 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!).


You should observe that this function is more or less sum which can be defined simply by using fold.

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

What does fold do? Basically, it's defined like so:

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

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

The issue here which you need to address is that + doesn't know how to operate on non-numeric values. No problem, you've already dealt with that. What happens if it's a character instead? Well, you're not adding anything to the total value, so replace it with a 0. Therefore, your solution is as simple as:

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


In Common 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

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜