• .Re: Working on learning lisp

    From Robert L.@21:1/5 to Rainer Joswig on Fri Feb 18 08:33:29 2022
    Rainer Joswig wrote:

    (defun split-string (string &optional (separators " ,-"))
    "Splits STRING into a list of substrings (which is returned)
    separated by the characters in the sequence SEPARATORS. Empty
    substrings aren't collected."
    (flet ((make-collector ()
    (make-array 0
    :adjustable t
    :fill-pointer t
    :element-type #+:lispworks 'lw:simple-char
    #-:lispworks 'character)))
    (loop with collector = (make-collector)
    for char across string
    for counter downfrom (1- (length string))
    when (find char separators :test #'char=)
    when (plusp (length collector))
    collect collector
    and do (setq collector (make-collector))
    (vector-push-extend char collector)
    else do (vector-push-extend char collector) end
    else
    do (vector-push-extend char collector)
    and when (zerop counter) collect collector)))


    (use srfi-13) ;; string-fold for Gauche Scheme
    or
    (require srfi/13) ;; string-fold for Racket

    (define (string-split-inclusive str . chars)
    (reverse
    (filter-map (lambda (xs)
    (and (pair? xs) (apply string (reverse xs))))
    (string-fold
    (lambda (c accum)
    (if (member c chars)
    (cons (list c) accum)
    (cons (cons c (car accum)) (cdr accum))))
    '(())
    str))))

    (string-split-inclusive "" #\; #\,)
    ===>
    ()

    (string-split-inclusive ";foo,bar;baz;" #\; #\,)
    ===>
    (";foo" ",bar" ";baz" ";")
    (";foo" ",bar" ";baz" ";")

    (string-split-inclusive "{pal}{buddy}{/buddy}{/pal}" #\{)
    ===>
    ("{pal}" "{buddy}" "{/buddy}" "{/pal}")

    --- SoupGate-Win32 v1.05
    * Origin: fsxNet Usenet Gateway (21:1/5)