Reputation: 23
I'm new to LISP and just started self learning. I want to print the value of p
side by side using write-line
. What I want to see is p=x
:
(setq p 10987)
(write-line "p=")
(write p)
the result looks like this:
p=
10987
I want to achieve p=10987
in the same line.
Upvotes: 0
Views: 673
Reputation: 21359
There is no need to use write-line
with format
; just use format
alone.
Note that setq
and setf
are intended for mutation of existing variables; they are not intended to establish new bindings, and the Common Lisp specification does not define any behavior for the posted code. Typically implementations do what you would expect, but don't attempt to define new variables using setq
or setf
in code that matters. Some implementations, e.g., SBCL, issue warnings in such cases.
Common ways to establish new bindings include defvar
, defparameter
, or let
:
CL-USER> (defparameter *p* 10987)
*P*
CL-USER> (format t "*p*=~A~%" *p*)
*p*=10987
NIL
Here defparameter
establishes a binding to *p*
; setf
or setq
could be used to update this binding now. Note that *p*
has earmuffs, which are conventionally used in Common Lisp to indicate dynamically scoped variables.
The first argument to format
specifies the output destination. If it is t
, then the output is to *standard-output*
; if nil
then format
returns a string result. You can also specify a particular stream, or an existing string with a fill pointer as destinations. The ~A
in the call to format
is the aesthetic directive, which usually does what you want when your goal is to print a value for a person to read. The ~%
directive causes format
to emit a newline; with this there is no need for write-line
to be used at all.
Another (more awkward) approach would be to use princ
and terpri
:
CL-USER> (let ((p 10987))
(princ "p=")
(princ p)
(terpri))
p=10987
NIL
Here p
is a locally scoped variable, hence no earmuffs. princ
is used to print an object in human-readable form, but it does not emit a newline. The arcanely-named terpri
emits a newline.
Upvotes: 3