2015-04-03 110 views
3

我想写一个方案函数,它将一个列表作为其输入并返回一个列表,其中包含所有元素,直到输入列表中的第一个数字元素。Scheme函数返回第一个数字

下面是一个例子:

(up-to-first-number '(a b c d 1 2 3)) ; returns (a b c d) 

我怎样才能做到这一点?

回答

3

在解释器中查找实现类似功能的现有过程。例如,在拍我们可以使用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)