[pro] The Best Examples of "Code is Data"

Mark Cox markcox80 at gmail.com
Sun Sep 5 22:31:19 UTC 2010


Hi,

I have a program which takes a mathematical expression for a polynomial and converts it to an equivalent polynomial of the form:

(+ (* ... ) (* ... ) (* ... ) ) 

where the .... contain only numbers and/or symbols.  e.g.

(* (+ A B) (- A B) ) gets converted to (+ (* A A) (* -1 B B))

Once in this "canonical" form I process the polynomial to produce a new function that returns the coefficients of the polynomial for a particular symbol. e.g.

> (do-polynomial-coefficients-function 'b '(a) '(+ (* A A) (* -1 B B) )
(LAMBDA (A) 
	(LIST -1           ; (* -1 (expt B 2) )
		    0           ; (*  0 (expt B 1) )
		    (+ (* A A))))

The list of coefficients can then be used to find the roots of the polynomial i.e. what are the values of B for which (zerop (* (+ A B) (- A B)) is true. 

The reason I wrote the expander is for the following 6th degree polynomial where I thought I would make more mistakes doing it by hand.

> (canonical-polynomial-coefficients-function t-value (a b c d f1 f2)
					(- (* t-value (expt (+ (expt (+ (* a t-value) b) 2.0)
					   		       (* (expt f2 2)
								  (expt (+ (* c t-value) d) 2)))
								        2))
					   (* (- (* a d) (* b c))
					      (expt (+ 1 (* f1 f1 t-value t-value)) 
						    2)
					      (+ (* a t-value) b)
					      (+ (* c t-value) d))))


The aspect I like most about "code is data", is the polynomial above is exactly as written in the text book. It is easy for me to check that it is right, it is also easy to document and think of the amount of paper I didn't need to use.

Mark

On 05/09/2010, at 10:24 PM, Kazimir Majorinc wrote:

> As first, good luck with this list!
> 
> I'm in search for best examples of "code is data" paradigm in Common
> Lisp. For most CL-ers, it probably means "macros", but eval, backquote,
> anything that processes the code as data is of interest. As "best" I
> think on the most surprising, powerful, sophisticated examples, not
> necessarily of a pedagogical value.
> 
> Imagine that someone invited you to write the presentation "Five best CL
> macros ... I seen" or "Five best CL macros ... I wrote." What would you
> chose and why?
> 
> Kazimir Majorinc
> 
> 
> 
> 
> 
> _______________________________________________
> pro mailing list
> pro at common-lisp.net
> http://common-lisp.net/cgi-bin/mailman/listinfo/pro





More information about the pro mailing list