我正在尝试在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
提前感谢您的帮助!
答案 0 :(得分:2)
你的第二个条件是错的:
((number? list) '())
您不使用number?
测试列表,您应该测试(car list)
,如果head元素是数字,则递归处理(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))))))
答案 1 :(得分: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
?也许你的错误存在于某个地方。
另请注意,通过调用您的参数list
,该过程中不再提供标准过程list
。这就是为什么你经常看到lst
用于表示Scheme代码中的列表参数的原因。