[plt-scheme] when to use define-struct?

From: Noel Welsh (noelwelsh at yahoo.com)
Date: Fri May 7 04:22:37 EDT 2004

--- Bill Richter <richter at math.northwestern.edu>
wrote:


> My question (very specific below) is when should we
> use define-struct?

When it is appropriate ;) (see below)

> Any time we have a class of objects, say Widget, we
> can use
> define-struct to specify lists of widgets, by 
...
> 
> So my general question is: is this considered to be
> useful?  

No.  Why not?  Because the data definition says
widgets are "a list of widget" so use a normal cons
list and you can use all the list functions defined on
lists.

> Monomial =lists of integers n >= 0
> 
> So (2 4 8) is a monomial.  The empty list is the
> "identity element."
> 
> I also define 
> Polynomial = lists of monomials 

Here I think structures would be useful.  Why? 
Because I don't think a monomial is actually a list of
numbers but rather you have chosen to represent a
monomial in such a way.  You could represent it
another way, for example using a tree.  If you define
structures to hold your data you can hide the
implementation details via modules:


(module monomial mzscheme

  (provide m+ m-)
  
  ; Monomial  = coefficients
  ; coefficients = list of number
  (define-struct monomial coefficient)

  (define (m+ m1 m2)
    (append (monomial-coefficients m1)
            (monomial-coefficients m2)))

  ...)

Now you can't mess up your types and you can
transparently switch to a more efficient
representation (e.g. an ordered tree) at a later date.

I'm sure the experts will have more insights to offer!

Noel

=====
Email: noelwelsh <at> yahoo <dot> com
Jabber: noelw <at> jabber <dot> org


	
		
__________________________________
Do you Yahoo!?
Win a $20,000 Career Makeover at Yahoo! HotJobs  
http://hotjobs.sweepstakes.yahoo.com/careermakeover 


Posted on the users mailing list.