Sujet : Re: Beginner code - splitting lines on whitespace
De : Nobody447095 (at) *nospam* here-nor-there.org (B. Pym)
Groupes : comp.lang.lispDate : 22. Jul 2024, 14:25:51
Autres entêtes
Organisation : A noiseless patient Spider
Message-ID : <v7lmkp$lo3u$1@dont-email.me>
References : 1
User-Agent : XanaNews/1.18.1.6
B. Pym wrote:
(defun white-space-p (c)
(or (char= c #\Space) (char= c #\Tab)))
(defun split-on-space (string)
(loop
for b = (position-if-not #'white-space-p string)
then (position-if-not #'white-space-p string :start e)
for e = (when b (position-if #'white-space-p string :start b))
while b
collect (subseq string b e)
while e))
Gauche Scheme
(use srfi-13) ;; string ops.
(define (white-space? c) (member c '(#\space #\tab)))
(define (split-on-space str :optional (start 0))
(let1 b (and start (string-skip str white-space? start))
(if b
(let1 e (string-index str white-space? b)
(cons (string-copy str b e) (split-on-space str e)))
'())))
(split-on-space " foo bar ")
===>
("foo" "bar")
(split-on-space "foo")
===>
("foo")
(split-on-space "")
===>
()
Another way:
(define-method object-apply ((s <string>) (i <integer>) j)
(string-copy s i j))
(define (split-on-space str :optional (start 0))
(let1 b (and start (string-skip str white-space? start))
(if b
(let1 e (string-index str white-space? b)
(cons (str b e) (split-on-space str e)))
'())))
The easy way.
(use srfi-13)
(define (split-on-space str)
(string-tokenize str))
Another way.
Gauche Scheme
(use srfi-13) ;; string ops.
(use gauche.generator)
(define (white-space? c) (member c '(#\space #\tab)))
(define (make-token-generator str)
(let ((str str)
(start 0)
(end 0))
(lambda ()
(set! start
(and start end (string-skip str white-space? end)))
(if start
(begin
(set! end (string-index str white-space? start))
(string-copy str start end))
(eof-object)))))
(define (split-on-space str)
(generator->list (make-token-generator str)))
(split-on-space "")
===>
()
(split-on-space " ")
===>
()
(split-on-space "foo")
===>
("foo")
(split-on-space " foo ")
===>
("foo")
(split-on-space " foo bar ")
===>
("foo" "bar")
(split-on-space " 3.14 foo? [bar] ")
===>
("3.14" "foo?" "[bar]")