Reputation: 153
Is there a way to extract only numbers within a list? I'm using the beginner language package so I cannot use filter which is a bummer.
(list a 1 2 b d 3 5) => 1 2 3 5 etc I want to use this as a part of my helper function but I cannot figure it out!
thanks!
Upvotes: 2
Views: 1122
Reputation: 236004
Ideally this problem should be solved using the filter
higher-order procedure, like this:
(filter number? '(a 1 2 b d 3 5))
=> '(1 2 3 5)
... But because this looks like a homework, I'll give you some hints on how to solve the problem by hand, just fill-in the blanks:
(define (only-numbers lst)
(cond (<???> ; is the list empty?
<???>) ; return the em´pty list
(<???> ; is the 1st element in the list a number?
(cons <???> ; then cons the first element
(only-numbers <???>))) ; and advance the recursion
(else ; otherwise
(only-numbers <???>)))) ; simply advance the recursion
Notice that this solution follows a well-known template, a recipe of sorts for recursively processing a list and in turn creating a new list as output. Don't forget to test your procedure:
(only-numbers '(a 1 2 b d 3 5))
=> '(1 2 3 5)
(only-numbers '(1 2 3 4 5))
=> '(1 2 3 5)
(only-numbers '(a b c d e))
=> '()
Upvotes: 4