1

I am trying to parse a comma separated string with Common lisp with the function below. For (separate-on-comma "a,b,c") I would expect the output ("a" "b" "c") but instead I get ("c" "c" "c"). What do I miss here?

(defun separate-on-comma (line)
    (loop
       with fields = () 
       with field = (make-array 0 :element-type 'character :adjustable t :fill-pointer 0)
       for x across line
       when (char= x #\,)        
       do (push field fields)
       and do (setf (fill-pointer field) 0)
       else
       do (vector-push-extend x field)
       finally 
     (push field fields)
     (return fields)))

Thanks.

3
  • 1
    Alternative: use the split-sequence library. Alternative implementation: use position and subseq in a loop. Commented Feb 27, 2015 at 0:00
  • 1
    > (ql:quickload :split-sequence) > (split-sequence:split-sequence #\, "a,b,c") ("a" "b" "c") Commented Feb 27, 2015 at 12:07
  • 1
    (progn (ql:quickload "cl-ppcre") (cl-ppcre:split "," "a,b,c")) >("a" "b" "c") Now you can even use regexps for splitting a string. Commented Feb 28, 2015 at 21:09

1 Answer 1

4

You are working only with one field array. That's okay. But you better copy it when you push it to the fields list variable. Use copy-seq.

Alternatively create a new field array once you pushed the old one onto the fields list.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.