From: Tamas Papp
Subject: format & typecase
Date: 
Message-ID: <87odioxt45.fsf@pu100877.student.princeton.edu>
Hi,

I would like to format something differently depending on its type.
For example,

(defun foo (value precision)
  (format nil "~[~,vF (float)~;~*~D (integer)~;~*~A (other)~]"
	  (typecase value
	    (float 0)
	    (integer 1)
	    (t 2))
	  precision
	  value))

CL> (foo 1 4)
"1 (integer)"
CL> (foo pi 4)
"3.1416 (float)"
CL> (foo "bar" 4)
"bar (other)"

I did it with ~[ and typecase, but I wonder if format could condition
on type, leading to a more compact version.

Thanks,

Tamas

From: Rainer Joswig
Subject: Re: format & typecase
Date: 
Message-ID: <2007070715233216807-joswig@lispde>
On 2007-07-07 15:04:26 +0200, Tamas Papp <······@gmail.com> said:

> Hi,
> 
> I would like to format something differently depending on its type.
> For example,
> 
> (defun foo (value precision)
>   (format nil "~[~,vF (float)~;~*~D (integer)~;~*~A (other)~]"
> 	  (typecase value
> 	    (float 0)
> 	    (integer 1)
> 	    (t 2))
> 	  precision
> 	  value))
> 
> CL> (foo 1 4)
> "1 (integer)"
> CL> (foo pi 4)
> "3.1416 (float)"
> CL> (foo "bar" 4)
> "bar (other)"
> 
> I did it with ~[ and typecase, but I wonder if format could condition
> on type, leading to a more compact version.
> 
> Thanks,
> 
> Tamas

You could also do:

(format
  nil
  (typecase bar
    (float ".....")
    (integer "...."))
  bar)



-- 
http://lispm.dyndns.org/
From: Kent M Pitman
Subject: Re: format & typecase
Date: 
Message-ID: <ulkdsvw8n.fsf@nhplace.com>
Tamas Papp <······@gmail.com> writes:

> (defun foo (value precision)
>   (format nil "~[~,vF (float)~;~*~D (integer)~;~*~A (other)~]"
> 	  (typecase value
> 	    (float 0)
> 	    (integer 1)
> 	    (t 2))
> 	  precision
> 	  value))
> 
> CL> (foo 1 4)
> "1 (integer)"
> CL> (foo pi 4)
> "3.1416 (float)"
> CL> (foo "bar" 4)
> "bar (other)"
> 
> I did it with ~[ and typecase, but I wonder if format could condition
> on type, leading to a more compact version.

I don't suppose this would do.  It's not quite what you'reasking for, but...

CL-USER 81 > (defun foo (stream thing colon-p at-sign-p &rest parameters)
               (declare (ignore colon-p at-sign-p parameters))
               (format stream "~S (~(~S~))" thing (type-of thing)))
FOO

CL-USER 82 > (format t "~/CL-USER::FOO/" 3)
3 (fixnum)
NIL

CL-USER 83 > (format t "~/CL-USER::FOO/" 3.14)
3.14 (double-float)
NIL