2017-04-04 94 views
0

我试图在Scheme中编写一个程序,该程序需要一个列表并返回仅包含非数字项目的列表。这似乎应该工作,但它只是打印整个列表。任何人都可以看到我在这里做错了吗?Scheme:遍历列表并仅返回非数字的程序

;;;up-to-first-number 
;;;takes a list as its input and returns a list containing all 
;;;the elements up to the first numeric element in the input list. 

;;test lists 
(define mylist '(a b c 1 2 3)) 
(define mylist2 '(1 2 2 4 5)) 


    (define (up-to-first-number list) 
     (cond 
     ((null? list)'()) ;if list is null, return null list 
     ((number? list) '()) ;if item is a number, return null list 
     (else (cons (car list) (up-to-first-number (cdr list)))))) ;else, add item to new list and recurse 

在此先感谢您的帮助!

回答

1

你的第二个条件是错误的:

((number? list) '()) 

你不number?测试列表,你应该测试(car list),递归处理(cdr list)如果头元素是一个数字。看看下面的代码:

(define (up-to-first-number lst) 
(cond 
((null? lst) '()) 
((number? (car lst)) (up-to-first-number (cdr lst))) 
(else (cons (car lst) (up-to-first-number (cdr lst)))))) 
+0

就是这样!汽车清单,而不仅仅是清单。这样一个简单的修复。谢谢!! – Ang

+0

很高兴帮助:-)如果您能接受它作为答案,我将不胜感激:-) – shizhz

0

有了这样一个简单的程序,你应该能够用手扣除..

(up-to-first-number '(1)) ; == 

(cond 
    ((null? '(1)) '()) 
    ((number? '(1)) '()) 
    (else (cons (car '(1)) (up-to-first-number (cdr '(1)))))) 

所以(null? '(1))#f如预期,但你可能会惊讶(number? '(1))#f太?也许你的bug在某处。

另请注意,通过调用您的参数list,标准程序list在该过程中不再可用。这就是为什么你经常看到lst被用来表示Scheme代码中的列表参数。