MOO-cows Mailing List Archive


Re: Scattering assignment

On Mon, 18 Nov 1996, Michael Moore wrote:
> How about a new reserved word-- "as", used for type checking.
> In simple assignment, 
>      <var> = <expr> AS <type>;
> Or, in scattered assignment,
>      {<var1>, <var2>} = {<expr1> AS <type>, <expr2> AS <type>};
> If the result of <expr> is not of type <type> then E_TYPE is raised.  (Or
> if the verb is !d then E_TYPE is assigned to <var>.)
>     z = <expr> AS {NUM, STR};
> You could probably take it even one level higher and allow an expression
> to the right of the 'as', which should return a NUM or a LIST of NUM.

Just as an initial, gut-level reaction, I think this is a pretty cool way of 
doing it; however, I think the "as" should definitely go on the LHS to 
allow you to easily do things such as

   {var1 as LIST, var2 as STR} = args;

I can't even remember what syntax I suggested when I first brought it 
up; I think Gustavo (or whoever brought it up the second time) suggested 
something like { STR: <var1>, LIST: <var2> } and some slightly more 
awkward way of handling the multiple cases.  (Sorry if I'm misquoting here;
for some reason I can't seem to find the article in question.)

In my opinion, the main advantage of your method (in addition to avoiding 
recasting the meaning of already used punctuation symbols such as : or #) is 
that as you noted, it allows constructs such as

  <var> as <type expr> = <assignment expr>

That is, <type expr> can return a (possibly dynamic) list of accepted 
types for var.

I'm tempted to add that it would be neat if we could have a custom 
type-checker.  For sake of argument, say this thing is called $typecheck(),
so that 
  <var> as <type expr> = <assignment expr>
is treated instead as
  <var> = $typecheck(<type expr>, <assignment expr>)

In this way, you could implement custom types; this functionality would 
mainly (only?) be useful for composite types, such as "list of strings".
However, the overhead involved seems likely to be so great that in those 
rare cases that you really need this functionality, then you should 
probably do it yourself (i.e., literally use
    <var> = $typecheck:(<type expr>, <assignment expr>)
instead of scattering)

In any event, I'm all for keeping things simple. :-)

> But this leads to strangeness like which error should be used if that
> expression returns the wrong type?  E_INVARG?  (Remember, E_TYPE woule be
> reserved for when the assignment didn't match the specified type.)
> And, again, I personally don't see much use for it.

It doesn't really lead to strangeness any more than
'expr ! {@expr_not_returning_a_list(), E_VERBNF} => expr_h'
does.  However, it does lead to some ambiguity, since it would be 
impossible to determine whether E_TYPE was really raised by an 
incompatible scattering assignment, or whether it was raised by one of 
the <type expr>'s themselves.  In practice that doesn't seem too



Home | Subject Index | Thread Index