Structs (was RE: Record selectors)
Ulf Wiger
etxuwig@REDACTED
Wed Jan 15 10:21:00 CET 2003
On Tue, 14 Jan 2003, Joe Armstrong wrote:
>Let me call the thing I like structs (to distinguish them
>from records).
>
> With structs you can write things like:
>
> A = ~{name="joe", footSize=42}, %% define a struct
> A.footSize, %% access a field
> B = ~A{likes="motorbikes"}, %% add a new field
I'm wary about the ease of which one can add a new field. It
has a feel of BASIC over it (mistyping a variable name
creates a new variable.) Erlang's dynamic typing of
variables is still reasonably safe from typos due to single
assignment (if you mis-type a variable name and then refer
to that variable without the typo, the compiler will
complain.)
Personally, I would prefer it if fields could only be added
using an add_field/2 function. I think it's an uncommon
operation. Most of the time, assigning a value to a
non-existing field is probably an error.
The issue of default values could be addressed for named
structs using the pre-processor:
-struct(guru, {name = "joe",
footSize = 42,
likes = "motorbikes"}).
Then, one could create a named struct just like a new
record:
C = ~guru{name = "robert", likes="water rockets"}.
But this would of course not solve the compile-time
dependencies that now plague records.
On the other hand, if one writes a module that is the "home"
of a struct, and makes sure to instantiate a struct using a
dedicated function, the issue of defaults is not a big one:
-module(mystructs).
-export([new/1]).
new(guru) ->
~guru{name, footSize, likes}.
...introducing some syntactic sugar that allows us to avoid
having to type "= undefined" for all fields that should have
a default value.
D = (mystructs:new(guru))~{name="klacke",
likes="whitewater rafting"}
This would also perhaps make it possible to introduce real
handling of undefined fields:
erlang:is_nil(D.footSize) -> true | false.
(where accessing a non-initialized field is an error.
I'm not totally convinced that this is a good idea, but
then again, we could stick to the heretic practice of
using the legal value 'undefined')
Anonymous structs could perhaps be kept super-dynamic. I
don't know if this would complicate the implementation or
compromise efficiency.
/Uffe
--
Ulf Wiger, Senior Specialist,
/ / / Architecture & Design of Carrier-Class Software
/ / / Strategic Product & System Management
/ / / Ericsson Telecom AB, ATM Multiservice Networks
More information about the erlang-questions
mailing list