Structs - thoughts on implementation

Robert Virding robert.virding@REDACTED
Mon Jan 20 00:05:37 CET 2003


Lawrie Brown wrote:
> Hi Joe & everyone
> 
> On Tue, Jan 14, 2003 at 10:41:44AM +0100, Joe Armstrong wrote:
>...

> Hence Ulf's example above would be represented by:
> 
>     C = {guru, dynamic_struct, likes, "water rockets", name, "robert"}
> 
> a statement like: D = ~C{likes="motorbikes"} results in:
> 
>     D = {guru, dynamic_struct, likes, "motorbikes", name, "robert"}
> 
> and a statement like: E = ~C{hates="skiing"} results in:
> 
>     E = {guru, dynamic_struct, hates, "skiing", likes, "water rockets", name, "robert"}
> 
> I think this has the nice advantage of being dynamic, self-documenting,
> and compatible with existing Erlang types (& distribution protocol).

Actually I like skiing. :-)

I wonder if this will be fast enough. If we are really serious about 
structs then we should them as a replacement for records sometime in the 
future, and this would be logN time with at least one atom comparison. 
When we introduced records users were very worried that they would be 
slower than using records straight off. It took some convincing.

How would you handle anonymous structs?

> 
> In terms of run-time support, I lean towards extending/overloading some of
> the tuple BIFs thus:
> 
>  + element(Var, Type, Tag) - checks Var is a struct of specified Type,
> 	and returns the Value associated with Tag (or undefined), a guard
> 
>  + setelement(Var, Type, Tag, Value) - checks Var is a struct of specified
> 	Type, and either updates the value associated with Tag if present
> 	or (provided it s dynamic struct) extends the struct to support
> 	the new Tag & Value inserted into the appropriate position
> 
>  + size(Var, Type) - checks Var is a struct of specified Type, and returns
> 	the number of fields in it (its arity)
> 
>  + struct(Var, Type) - a recognizer for a struct of specified Type (cf record)
> 
> And whilst the stored form would be basically a tuple, it'd be easy enough to
>   add a flag to say it was created as a struct to improve efficiency.
> 
> And of course you need the compiler to recognise the new syntax. Also need
> some way of saying the you want a static struct (with tags fixed upon
> creation) vs a dynamic one.
> 
> Comments????

It would be an relatively easy way of properly introducing structs into 
the language, not just as pass to the compiler. I am a bit wary of 
overloading BIFs too much. I know I am guilty of doing it in the past 
but it was probably wrong in many cases.


Robert




More information about the erlang-questions mailing list