Subject: Re: coerce rational into complex float
From: (Rob Warnock)
Date: 21 Jul 2002 03:22:53 GMT
Newsgroups: comp.lang.lisp
Message-ID: <ahd9ed$a9d7u$>
Dave Bakhash  <> wrote:
| (Wolfhard Bu�) writes:
| >  (coerce <rational> '(complex float))
| > with a complex float?  CLtL2 seems to suggest a complex float, as
| > one would expect.  What is the opinion of the fine CLHS?
| In case it's useful information, this coercion works in ACL and LW.

Well, maybe it *doesn't* "work"; see below...  ;-}

In CLISP (admittedly an older one):

	(coerce 3.14 '(complex float))	==> #C(3.14 0.0)
[1]	(coerce 22/7 '(complex float))	==> #C(3.142857 0.0)
[2]	(coerce 22/7 'complex)		==> 22/7
	(coerce 22/7 'float)		==> 3.142857

And CMUCL (also an old one):

	(coerce 3.14 '(complex float))	==> #C(3.14 0.0)
[3]	(coerce 22/7 '(complex float))	==> 22/7
[4]	(coerce 22/7 'complex)		==> 22/7
	(coerce 22/7 'float)		==> 3.142857

Hmmm... Looks like CMUCL may be doing the right thing here
in cases #3 & #4 above, CLISP in case #2, while CLISP may be
doing the wrong thing in case #1.  The CHLS "Function COERCE" says:

	Otherwise, the object is coerced to type result-type
	according to the following rules:
	[list of result-types]
	    (If the real part is a rational, however, then the result
	    must be represented as a rational rather than a complex;
	    see Section (Rule of Canonical Representation for
	    Complex Rationals). So, for example, (coerce 3 'complex)
	    is permissible, but will return 3, which is not a complex.)

And CLHS (non-glossary links in caps):

	If the result of any computation would be a complex number whose
	real part is of type RATIONAL and whose imaginary part is zero,
	the result is converted to the rational which is the real part.

So CMUCL does the right thing here, too:

	(coerce 4 '(complex float))	==> 4
	(coerce 4 'complex)		==> 4
	(coerce 4 'float)		==> 4.0


	This rule does not apply to complex numbers whose parts are
	floats. For example, #C(5 0) and 5 are not different objects
	in Common Lisp (they are always the same under EQL); #C(5.0 0.0)
	and 5.0 are always different objects in Common Lisp (they are
	never the same under EQL, although they are the same under
	EQUALP and =).


Rob Warnock, 30-3-510		<>
SGI Network Engineering		<>
1600 Amphitheatre Pkwy.		Phone: 650-933-1673
Mountain View, CA  94043	PP-ASEL-IA

[Note: and aren't for humans ]