我想编写一个scheme函数,它以列表作为输入,并返回一个列表,其中包含输入列表中第一个数字元素之前的所有元素。
以下是一个例子:
(up-to-first-number '(a b c d 1 2 3)) ; returns (a b c d)
我该怎么做?
答案 0 :(得分:5)
在解释器中查找实现类似功能的现有过程。例如,在Racket中我们可以使用takef
- 以下简单地说明所有不数字的元素都是从列表中获取的,当我们找到第一个数字时我们停止:
(define (up-to-first-number lst)
(takef lst (negate number?)))
即使您使用不同的口译员,也可以始终使用SRFI-1 take-while
获得类似的效果:
(require srfi/1) ; import the library, read your interpreter's documentation
(define (up-to-first-number lst)
(take-while (lambda (x) (not (number? x))) lst))
作为最后的手段,你可以手工编写一个实现 - 它非常简单,我不想破坏乐趣,所以我只给你一些提示。用适当的表达式填空:
(define (up-to-first-number lst)
(if (or <???> ; if either the list is empty
<???>) ; or the first element is a number
<???> ; then return the empty list
(cons <???> ; otherwise cons the first element
(up-to-first-number <???>)))) ; and advance the recursion
您选择的实施方案并不重要,您可以测试它是否按预期工作:
(up-to-first-number '(a b c d 1 2 3))
=> '(a b c d)
答案 1 :(得分:0)
(define (up-to-first-number list)
(cond
;;if the list is null return an empty list
((null? list)
'())
;;if the first element is a number then there are no preceeding
;;letters in the list so return an empty list
((number? (car list)) '())
;;else the first element is not a number so add that element
;;to a new list and recursively call method on the remaining
;;elements in the list
(else (cons (car list) (up-to-first-number (cdr list) )))))