Skip to content

Instantly share code, notes, and snippets.

@abishek
Created August 8, 2020 12:45
Show Gist options
  • Save abishek/07c3cdcf6e13635bc6204c47ab07a3bb to your computer and use it in GitHub Desktop.
Save abishek/07c3cdcf6e13635bc6204c47ab07a3bb to your computer and use it in GitHub Desktop.
A simple defun to split a space separated string into individual word strings. "one two three" into ("one" "two" "three") so to say.
(defun split-sentence-to-words (sentence)
(let ((word '()))
(loop for ch across sentence
if (member ch '(#\space #\tab #\,))
collect (coerce (reverse word) 'string) into words and do (setf word '())
else
do (push ch word)
finally (return (append words (coerce (reverse word) 'string))))))
@abishek
Copy link
Author

abishek commented Aug 9, 2020

@RainerJoswig on twitter helped me out: https://twitter.com/rainerjoswig/status/1292183185867120641?s=21

Here is my fixed version taking inspiration from his sample.

(defun create-word (chars)
  (coerce (reverse chars) 'string))

(defun split-sentence-to-words (sentence &optional (separators '(#\space #\tab #\,)))
  (let ((chars '()))
    (append
     (loop for ch across sentence
           if (member ch separators)
             if chars collect (create-word chars) and do (setf chars '()) end
               else do (push ch chars))
     (if chars (list (create-word chars))))))

Yes, I could copy the aux and the flet. But these are things I am not super familiar with. So I'll stick to what I know until I grow up some more. But the real trick I needed was where the append is used.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment