[plt-scheme] The role of proper and improper lists?

From: Ethan Herdrick (info at reatlas.com)
Date: Sat Jan 26 00:22:30 EST 2008

Hi Grant

If I'm dealing with key-value pairs I use the second style you
mentioned: (cons 'key 'value)  It's nice and symmetrical: the car gets
the key and the cdr gets the value.  As you may already know, a list
of those, like the one you mentioned, (list (cons 'a 1) (cons 'b 2)
(cons 'c 3)), is then an association list, so you can use assoc to
retrieve a key-value pair by passing in the key.  It's equivalent to a
hash table.  In fact, most Schemes have a function, alist->hashtable,
(and its inverse) for switching between the two.

I'll throw my opinion in on the list vs struct vs object question.  I
prefer lists (association lists or otherwise) more or less always.  I
think you are better off just jamming your data into lists and making
a comment to explain what those values are for.  If your project grows
to the point where this lack of explicit structure starts to bother
you, then if you like you can refactor over to something like a struct
or an object or whatever.  If your project is for school, then it's
already fairly well-defined; you know whether it will be big or not
when you start.  But otherwise, lots of projects die early and it
would be a shame to put effort into carefully structuring data your
for those.

-Ethan

On Jan 24, 2008 7:24 PM, Grant Rettke <grettke at acm.org> wrote:
> I'm working on the problems in
> _The_Scheme_Programming_Language_3rd_Edition and I came upon a problem
> that made me think about improper lists. The thing about which I was
> wondering was when you would use an improper list rather than a proper
> list. A simple contrived example about which I was thinking.
>
> Suppose you got a list of key-pair values. You could assemble it, for
> example, in one of the two ways:
>
> (list (list 'a 1) (list 'b 2) (list 'b 3))
>
> or
>
> (list (cons 'a 1) (cons 'b 2) (cons 'c 3))
>
> when you grab one of the key-pair values you could retrieve the key
> and the pair with
>
> (car (list 'a 1))
> (cadr (list 'a 1))
>
> for the former or
>
> (car (cons 'a 1))
> (cdr (cons 'a 1))
>
> So there are two ways of doing... the same thing? Is it the same?
>
> An improper list is *not* terminated with the empty list, a proper
> list is terminated:
>
> (cons 1 2)
>
> versus
>
> (cons 1 (cons 2 '()))
>
> Where/when/why does this matter?
> _________________________________________________
>   For list-related administrative tasks:
>   http://list.cs.brown.edu/mailman/listinfo/plt-scheme
>


Posted on the users mailing list.