Friday, September 16, 2022

[FIXED] Why inserting `format` function inside a `dolist` expression does not work in Common Lisp?

Issue

I am using SBCL, Eamcs, and Slime. Using the print function, I can do:

CL-USER> (dolist (item '(1 2 3))
           (print item))
1 
2 
3 
NIL

In addition, format function works for single elements:

CL-USER> (format nil "~a" 1)
"1"

Why the following insertion of format function inside dolist does not work?

CL-USER> (dolist (item '(1 2 3))
           (format nil "~a" item))
NIL

I was expecting to see all elements of the list processed by the format function.

Thanks


Solution

The answer to this is that the first argument to format denotes a destination for the formatted output. It may be one of four things:

  • a stream, to which output goes;
  • t which denotes the value of the *standard-output* stream;
  • nil which causes format to return the formatted output rather than print it;
  • or a string with a fill pointer, which will append the output to the string at the fill pointer.

So (format nil ...) does not print anything: it returns something.



Answered By - ignis volens
Answer Checked By - Willingham (PHPFixing Volunteer)

No comments:

Post a Comment

Note: Only a member of this blog may post a comment.