2015-04-03 113 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)