2014-11-21 89 views
0

我試圖找出編碼方法的方法,以便從包含字母和數字的列表中返回字母,它應該返回字母到列表中的第一個數字。例如: (up-to-first-digit '(q w c 9 5 6)) returns (q w c)到目前爲止,我有「第一個」定義的功能:(define (frst a b) a),但不能想到實現此操作將字母返回到第一個數字,儘管我不限於使用我定義的函數。任何想法,想法?謝謝!注意:我僅限於使用某些預定義的謂詞,例如我在考慮keep僅保留字符串,但它又會返回第一個數字。In Scheme如何僅返回包含字符串和數字組合的列表中的字符串

回答

3
(define (take-while p l) 
    (let loop ((o '()) (l l)) 
    (if (and (not (null? l)) (p (car l))) 
     (loop (cons (car l) o) (cdr l)) 
     (reverse o)))) 

(define (up-to-first-digit l) 
    (take-while (lambda (x) (not (number? x))) l)) 

(up-to-first-digit '(q w c 9 5 6)) ;=> (q w c) 
+4

可能會提到的是'通吃while'是一個標準程序[SRFI- 1 List library](http://srfi.schemers.org/srfi-1/srfi-1.html#Searching) – Sylwester 2014-11-21 14:32:28

+0

如果它使用'cond',它也會更好看; p – leppie 2014-11-21 17:05:51

+2

@leppie不需要使用'cond '當一個單獨的'if'會做。 – 2014-11-21 20:21:43

2

上的術語只是一個字:你真正尋找的是符號,而不是字母;-)

(define (first-syms x) 
    (if (and (pair? x) (symbol? (car x))) 
     (cons (car x) (first-syms (cdr x))) 
     '())) 
相關問題