scheme的split实现

再chez中并未找到一个split函数,基于尾递归,自己实现了了一个用于字符串拆分的split。

(define split
      (lambda (str sep)
        (define loop
             (lambda (str sep result)
                  (let ((l_str (string-length str))
                        (l_sep (string-length sep)))
                    (cond
                      ((< l_str l_sep)  (cons (string-append (car result) (substring str 0 1) ) (cdr result)))
                      ((= l_str l_sep)
                       (cond
                         ((string=? (substring str 0 l_sep) sep) result)
                         (else
                           (cons
                             (string-append (car result) (substring str 0 l_sep) )
                            (cdr result)))))
                      (else
                        (cond
                          ((string=? (substring str 0 l_sep) sep) (loop (substring str l_sep l_str) sep (cons "" result)))
                          (else
                            (loop (substring str 1 l_str) sep (cons (string-append (car result) (substring str 0 1) ) (cdr result))))))))))
          (reverse (loop str sep '("")))))

在chez下测试成功。

例如:

> (split "How are you? I/m fine thank you" " ")
("How" "are" "you?" "I/m" "fine" "thank" "you")
> (split "12@345@@678@@@910" "@@")
("12@345" "678" "@910")。

然后,先这样把。

posted @ 2019-01-07 16:36  Goodpy  阅读(272)  评论(0编辑  收藏  举报