struct

Sam Ruby rubys at intertwingly.net
Tue Jun 9 11:05:38 PDT 2009


At the last meeting, Mark Miller committed to explore creating a
proposal involving double-dispatch and value types.  Upon reflection,
I remembered that ECMA 334 defines "struct":

http://en.csharp-online.net/ECMA-334:_18._Structs

Without delving into syntax, though I do note that "struct" is not a
reserved word in ECMAScript, this type of concept does seem to address
the basic requirements that Mark was going to pursue, and additionally
addresses some of the secondary characteristics (such as not
necessarily requiring heap allocation) that Brendan alluded to in the
discussion.

Independent of any discussion of predefined numeric types, I believe
that there is a class of performance critical applications that could
benefit from an introduction of "structs" into ES.  Additionally, such
an addition could make ES more attractive as a compilation target (I
say while glancing meaningfully in the direction of Allen).

Since implementations will be free to (but not required to) copy the
value instead of the reference, it is important that the triple equals
operator compares the values for struct types.  Double equals can
implement different semantics.

Taking Rational as an example, the following makes sense to me.  Anybody differ?

  Rational(2,1) ==  2             ==> true
  Rational(1,2) ==  Rational(2,4) ==> true
  Rational(2,1) === 2             ==> false
  Rational(1,2) === Rational(2,4) ==> false

Given the above, the answer to the below is less clear:

  foo = {}
  foo[Rational(4,2)]='a'
  foo[Rational(2,1)]='b'
  foo[2]='c'

  foo[Rational(2,1)] ==> 'b' ???
  foo[Rational(4,2)] ==> 'a' ???

The motivation for the above is the question of whether or not there
will be the possibility of any user visible cohorts.

Double dispatch also provides an opportunity to mitigate the usability
problem that Brendan often laments.  While the Rational package can
provide a default implementation for a set of operator overloads (I'll
note that every double precision binary floating number has an exact
representation in terms of a rational number, something that is not
true in reverse), users that desire different behavior can simply
replace these operators.  This could even be done globally (a big red
switch, as Brendan seems to prefer).

The syntax question remains open, particularly for literals.

- Sam Ruby


More information about the es-discuss mailing list