<?xml version="1.0" encoding="utf-8"?>
<feed xmlns="http://www.w3.org/2005/Atom">
    <title>Francis Cheng</title>
    <link rel="alternate" type="text/html" href="http://blogs.adobe.com/fcheng/" />
    <link rel="self" type="application/atom+xml" href="http://blogs.adobe.com/fcheng/atom.xml" />
   <id>tag:blogs.adobe.com,2008:/fcheng/193</id>
    <link rel="service.post" type="application/atom+xml" href="http://blogs.adobe.com/cgi-bin/mt-atom.cgi/weblog/blog_id=193" title="Francis Cheng" />
    <updated>2008-05-15T23:44:28Z</updated>
    <subtitle>ActionScript, ECMAScript and the Flash Platform</subtitle>
    <generator uri="http://www.sixapart.com/movabletype/">Movable Type 3.2</generator>
 
<entry>
    <title>ECMAScript 4 Object Initializers and Type Annotations</title>
    <link rel="alternate" type="text/html" href="http://blogs.adobe.com/fcheng/2008/05/ecmascript_4_object_initialize.html" />
    <link rel="service.edit" type="application/atom+xml" href="http://blogs.adobe.com/cgi-bin/mt-atom.cgi/weblog/blog_id=193/entry_id=5895" title="ECMAScript 4 Object Initializers and Type Annotations" />
    <id>tag:blogs.adobe.com,2008:/fcheng//193.5895</id>
    
    <published>2008-05-15T23:29:02Z</published>
    <updated>2008-05-15T23:44:28Z</updated>
    
    <summary> My previous post was about ECMAScript 4 object initializers and fixtures. In this post, I&apos;m going to talk about another new feature of ECMAScript 4 object initializers: type annotations. That&apos;s right, in ES4 you&apos;ll be able to place type...</summary>
    <author>
        <name>Francis Cheng</name>
        <uri>http://blogs.adobe.com/fcheng</uri>
    </author>
            <category term="ECMAScript" />
    
    <content type="html" xml:lang="en" xml:base="http://blogs.adobe.com/fcheng/">
        <![CDATA[<p>
My previous post was about ECMAScript 4 object initializers and fixtures. In this post, I'm going to talk about another new feature of ECMAScript 4 object initializers: type annotations. That's right, in ES4 you'll be able to place type annotations on object initializers. To recap, an object initializer, a.k.a. an object literal, is often used in ActionScript 3 instead of the <code>new</code> operator to create an instance of the Object class. For example:
</p>

<pre>
var techWriter:Object = {fname:"Francis", lname:"Cheng", company:"Adobe"};
</pre>]]>
        <![CDATA[<p>
In ActionScript 3.0, you can use object initializers exclusively with the Object class. Once this new feature of ES4 gets rolled in to ActionScript, however, you will be able to use object initializers with other classes. Here's how it will probably work: place a type annotation after the closing curly brace. Let's say I have a simple class named Employee:
</p>

<pre>
class Employee {
  var fname;
  var lname;
  var company;
}
</pre>

With ECMASCript 4, I'll be able to create an instance of Employee using an object initializer:

<pre>
// ECMAScript 4th Edition code
var techWriter:Employee = {fname:"Francis", lname:"Cheng", company:"Adobe"}:Employee;
</pre>
<p>
One thing to keep in mind is that this will only work if all the fields of the object literal are of the form "fieldName:value". So what's the point of including this capability? The rationale comes from the idea of "evolutionary programming", which refers to the idea of moving from a more informal, scripting-based way of programming to a more structured and formal way of programming. Say you start with a simple script that provides rudimentary interactivity on your web page. As time goes by, you may decide to add more features to the script. At some point, you may find that the script is getting so complex that some formal structure would help. The idea of evolutionary programming is that the language should help you transition from the informal style to the formal style.
</p>
<p>
Type annotations on object initializers is an example of a feature that facilitates the transition from informal to formal programming style. In the example above, you can see how I moved from using a simple instance of the Object class to the more formal structure of an Employee class. Another feature that helps with this type of transitional programming is structural types, which allows you to create an simple type without creating a class. To give you a better sense of what evolutionary programming means, let's step through the transition again, but this time with a structural type thrown into the mix.
</p>
<p>
First, I start with an instance of the generic Object class:
</p>
<pre>
var techWriter:Object = {fname:"Francis", lname:"Cheng", company:"Adobe"};
</pre>

<p>
Second, I decide to get a little more formal by creating a structural type to represent employees:
</p>
<pre>
// ES4 structural type definition
type Employee = {fname:String, lname:String, company:String}
</pre>
<p>
Third, I can now create instances of the Employee type with an object initializer or with the new operator:
</p>
<pre>
// ES4 object initializer
var techWriter:Employee = {fname:"Francis", lname:"Cheng", company:"Adobe"}:Employee;

// ES4 new operator can be used with structural types
var techWriter2:Employee = new Employee("Francis", "Cheng", "Adobe")
</pre>
<p>
Finally, I can replace the structural type with a class:
</p>
<pre>
class Employee {
  var fname;
  var lname;
  var company;
}
</pre>
<p>So both structural types and type annotations on object initializers provide flexibility in the transition from using plain Object instances to instances of a class. For example, after I define the Employee class, there's no need for me to rewrite the instantiation code I wrote in step three because the code works for both the structural type and the class. 
</p>
<p>
Here's a list of relevant links:
</p>

<ul>
  <li><a href="http://www.ecmascript.org/es4/spec/evolutionary-programming-tutorial.pdf">A tutorial on Evolutionary Programming, by Lars T Hansen</a></li>
  <li><a href="http://bugs.ecmascript.org/ticket/370">ECMAScript trac ticket: Nominal type annotation on array and object literals</a></li>
</ul>]]>
    </content>
</entry>
<entry>
    <title>Object Initializers and Fixtures for ECMAScript 4th Edition</title>
    <link rel="alternate" type="text/html" href="http://blogs.adobe.com/fcheng/2008/04/object_initializers_enhanced_f.html" />
    <link rel="service.edit" type="application/atom+xml" href="http://blogs.adobe.com/cgi-bin/mt-atom.cgi/weblog/blog_id=193/entry_id=5652" title="Object Initializers and Fixtures for ECMAScript 4th Edition" />
    <id>tag:blogs.adobe.com,2008:/fcheng//193.5652</id>
    
    <published>2008-04-16T18:30:00Z</published>
    <updated>2008-04-16T18:37:45Z</updated>
    
    <summary> A recently released ECMAScript 4 draft specification for object initializers includes significant enhancements to the expressive power of object initializers. This post focuses on the ability to designate specific properties as fixtures, which is not possible in ECMAScript 3rd...</summary>
    <author>
        <name>Francis Cheng</name>
        <uri>http://blogs.adobe.com/fcheng</uri>
    </author>
            <category term="ECMAScript" />
    
    <content type="html" xml:lang="en" xml:base="http://blogs.adobe.com/fcheng/">
        <![CDATA[<p>
A recently released ECMAScript 4 draft specification for object initializers includes significant enhancements to the expressive power of object initializers. This post focuses on the ability to designate specific properties as fixtures, which is not possible in ECMAScript 3rd edition or ActionScript 3.0. 
</p>
<p>
You may have used object initializers in ActionScript 3.0 before. They provide an easy way to assign a literal value to a variable of type Object. For example, in ActionScript 3.0, you may see something like:
</p>

<textarea cols=65 rows=2 READONLY>
var myObj:Object = {name:"foo", color:"red"};
trace(myObj.name, myObj.color); // foo red
</textarea>
]]>
        <![CDATA[<p>
This creates an object called <code>myObj</code> with two dynamic properties, <code>name</code> and <code>color</code>. The properties are dynamic in that they are not defined as part of the Object class and can be deleted at runtime. For example, the following code deletes the <code>name</code> property:
</p>

<textarea cols=80 rows=3 READONLY>
// ActionScript 3.0
var myObj:Object = {name:"foo", color:"red"};
delete myObj.name;
trace(myObj.name, myObj.color); // undefined red
</textarea>

<p>
In ActionScript 3.0, if you want to ensure that the <code>name</code> property cannot be deleted at runtime, you have to define a class and make <code>name</code> a member, or "trait", of that class. In ActionScript 3.0, a trait is a class member that cannot be deleted at runtime. In ECMAScript 4, traits are called "fixtures", but you don't have to create a class definition to create a fixture. In fact, you can create fixtures with object initializers. For example, let's say you want to make the <code>name</code> property a fixture, so that runtime code cannot delete the property. In ES4, you'll be able to do this:
</p>
<textarea cols=80 rows=3 READONLY>
// ECMAScript 4 proposed
var myObj = {var name:"foo", color:"red");
delete myObj.name // error in strict mode, otherwise no effect
</textarea>
<p>
What if you want both <code>name</code> and <code>color</code> to be fixtures? All you have to do is place the "var" keyword before the curly braces. Doing so will make every property you name a fixture, like so:
</p>
<textarea cols=80 rows=4 READONLY>
// ECMAScript 4 proposed
var myObj = var {name:"foo", color:"red");
delete myObj.name; // error in strict mode, otherwise no effect
delete myObj.color; // error in strict mode, otherwise no effect
</textarea>
<p>
The fun doesn't stop there, though. Let's say you like creating objects on the fly like this, but that you'd want each object to have a unique ID number property that not only is a fixture, but also is a constant (i.e. read-only). All you have to do is use the keyword <code>const</code> instead of <code>var</code>:
</p>
<textarea cols=80 rows=4 READONLY>
// ECMAScript 4 proposed
var myObj = {const id:1, name:"foo", color:"red");
delete myObj.id; // error in strict mode, otherwise no effect
myObj.id = 2;    // error in strict mode, otherwise no effect
</textarea>

<p>
You can also use the <code>const</code> keyword before the curly braces if you want to make all of the properties you name read-only fixtures.
</p>
<textarea cols=80 rows=4 READONLY>
// ECMAScript 4 proposed
var myObj = const {id:1, name:"foo", color:"red");
myObj.id = 2;  // error in strict mode, otherwise no effect
myObj.name = "other";    // error in strict mode, otherwise no effect
</textarea>
<p>
Here's a list of relevant links:
</p>
<ul>
  <li><a href="https://mail.mozilla.org/pipermail/es4-discuss/attachments/20080410/d708d6fa/attachment-0001.html">Draft 3 of the Object Initializer specification posted by Lars Hansen on ES4-Discuss</a></li>
  <li><a href="https://mail.mozilla.org/pipermail/es4-discuss/2008-March/002383.html">Lars Hansen post on ES4-Discuss  about first draft of Object Initializers spec</a></li>
  <li><a href="https://mail.mozilla.org/pipermail/es4-discuss/2008-April/002659.html">Lars Hansen post on ES4-Discuss  about second draft of Object Initializers spec</a></li>
  <li><a href="https://mail.mozilla.org/pipermail/es4-discuss/2008-April/002668.html">Lars Hansen post on ES4-Discuss  about third draft of Object Initializers spec</a></li>
</ul>
]]>
    </content>
</entry>
<entry>
    <title>Flash Player Public Bugbase Introduced</title>
    <link rel="alternate" type="text/html" href="http://blogs.adobe.com/fcheng/2008/04/flash_player_public_bugbase_in.html" />
    <link rel="service.edit" type="application/atom+xml" href="http://blogs.adobe.com/cgi-bin/mt-atom.cgi/weblog/blog_id=193/entry_id=5585" title="Flash Player Public Bugbase Introduced" />
    <id>tag:blogs.adobe.com,2008:/fcheng//193.5585</id>
    
    <published>2008-04-09T00:55:13Z</published>
    <updated>2008-04-09T00:56:17Z</updated>
    
    <summary>Today, Adobe&apos;s Flash Player team introduced the new public bug and issue tracking system. This replaces the old wishform where you submitted bugs and enhancement requests but could not track the issue&apos;s progress. The new system is based on the...</summary>
    <author>
        <name>Francis Cheng</name>
        <uri>http://blogs.adobe.com/fcheng</uri>
    </author>
            <category term="Flash Player" />
    
    <content type="html" xml:lang="en" xml:base="http://blogs.adobe.com/fcheng/">
        <![CDATA[<p>Today, Adobe's Flash Player team introduced the <a href="https://bugs.adobe.com/flashplayer/">new public bug and issue tracking system</a>. This replaces the old wishform where you submitted bugs and enhancement requests but could not track the issue's progress. The new system is based on the same JIRA issue tracking system already in use by the Flex and Core ActionScript teams. This means that you will be able to first search to see whether someone has already reported the issue. If you find that someone has done so, you can vote for that issue to raise its visibility. Thereafter, you can track the issue's progress. Here's the official announcement of the page and another link to the page itself:
</p>

<ul>
  <li><a href="http://www.adobe.com/devnet/logged_in/tmccauley_fplayer_bugbase.html">Introducing the Flash Player bug and issue management system</a></li>
  <li><a href="https://bugs.adobe.com/flashplayer/">Adobe Bug and Issue Management System</a></li>
</ul>]]>
        
    </content>
</entry>
<entry>
    <title>New Draft of ECMAScript 4 Edition Grammar Released</title>
    <link rel="alternate" type="text/html" href="http://blogs.adobe.com/fcheng/2008/03/new_draft_of_ecmascript_4_edit.html" />
    <link rel="service.edit" type="application/atom+xml" href="http://blogs.adobe.com/cgi-bin/mt-atom.cgi/weblog/blog_id=193/entry_id=5526" title="New Draft of ECMAScript 4 Edition Grammar Released" />
    <id>tag:blogs.adobe.com,2008:/fcheng//193.5526</id>
    
    <published>2008-03-31T18:53:22Z</published>
    <updated>2008-03-31T19:02:31Z</updated>
    
    <summary> Adobe&apos;s Jeff Dyer has released a new draft of the ECMAScript 4th Edition normative grammar. The updated draft is available in both PDF and XLS formats. Here are the relevant links: Normative Grammar Proposal on the ECMAScript Wiki site,...</summary>
    <author>
        <name>Francis Cheng</name>
        <uri>http://blogs.adobe.com/fcheng</uri>
    </author>
            <category term="ECMAScript" />
    
    <content type="html" xml:lang="en" xml:base="http://blogs.adobe.com/fcheng/">
        <![CDATA[<p>
Adobe's Jeff Dyer has released a new draft of the ECMAScript 4th Edition normative grammar. The updated draft is available in both PDF and XLS formats. Here are the relevant links:
</p>

<ul>
  <li><a href="http://wiki.ecmascript.org/doku.php?id=proposals:normative_grammar">Normative Grammar Proposal on the ECMAScript Wiki site, with links to both PDF and XLS versions</a></li>
  <li><a href="http://www.ecmascript.org/es4/spec/grammar.pdf">Direct link to the PDF version of the normative grammar</a></li>
  <li><a href="http://www.ecmascript.org/es4/spec/grammar.xls">Direct link to the XLS version of the normative grammar</a></li>
  <li><a href="https://mail.mozilla.org/pipermail/es4-discuss/2008-March/002564.html">Jeff's announcment to the ES4-Discuss mailing list about the updated grammar</a></li>
</ul>]]>
        <![CDATA[For those keeping track, here are the changes from the last update (as listed on the <a href="http://wiki.ecmascript.org/doku.php?id=proposals:normative_grammar">normative grammar proposal page on ecmascript.org</a>):
<ul>
  <li>Rename ListExpression to CommaExpression; </li>
  <li>Make CommaExpression a binary expression in the AST;</li>
  <li>Change ParenExpression to ParenListExpression in SuperExpression;</li>
  <li>Rename ParenListExpression to ParenExpression;</li>
  <li>Remove Path qualified PropertyNames;</li>
  <li>Mark reserved/deferred features with ‘x’;</li>
  <li>Remove ‘wrap’;</li>
  <li>Remove ‘like’ as a type;</li>
  <li>Add ‘like’ as a binary type operator;</li>
  <li>Remove LetStatement;</li>
  <li>Remove UnitDefinition;</li>
  <li>Fold NullableTypeExpression into TypeExpression;</li>
  <li>Remove OverloadedOperator from QualifiedNameIdentifier;</li>
  <li>Add distinguishing syntax for tuples and array types in ArrayType;</li>
  <li>Add SplatExpression to arguments and array literals; </li>
  <li>Add RestPattern to array patterns; </li>
  <li>Add to ReservedIdentifiers ‘type’;</li>
  <li>Add to ContextuallyReservedIdentifiers ‘external’;</li>
  <li>Removed from ContextuallyReservedIdentifiers ‘decimal’, ‘double’, ‘generic’, ‘int’, ‘Number’, ‘precision’, ‘rounding’, ‘standard’, ‘to’, ‘uint’, ‘unit’; </li>
  <li>Add LikedPattern to Parameter;</li>
  <li>Add ‘like’ predicate to ResultType;</li>
  <li>Remove ParameterKind and use in Parameter</li>
</ul>
                 ]]>
    </content>
</entry>
<entry>
    <title>Proper Tail Calls Dropped from ECMAScript 4th Edition</title>
    <link rel="alternate" type="text/html" href="http://blogs.adobe.com/fcheng/2008/03/proper_tail_calls_dropped_from.html" />
    <link rel="service.edit" type="application/atom+xml" href="http://blogs.adobe.com/cgi-bin/mt-atom.cgi/weblog/blog_id=193/entry_id=5519" title="Proper Tail Calls Dropped from ECMAScript 4th Edition" />
    <id>tag:blogs.adobe.com,2008:/fcheng//193.5519</id>
    
    <published>2008-03-31T04:59:01Z</published>
    <updated>2008-03-31T05:49:33Z</updated>
    
    <summary>Brendan Eich reports that the Proper Tail Calls proposal for ECMAScript 4th Edition has been dropped. Brendan mentioned in a posting to the ES4-Discuss list yesterday that the proposal was dropped at the committee meeting last Friday: &quot;...(news flash) proper...</summary>
    <author>
        <name>Francis Cheng</name>
        <uri>http://blogs.adobe.com/fcheng</uri>
    </author>
            <category term="ECMAScript" />
    
    <content type="html" xml:lang="en" xml:base="http://blogs.adobe.com/fcheng/">
        <![CDATA[<p>Brendan Eich reports that the Proper Tail Calls proposal for ECMAScript 4th Edition has been dropped. Brendan mentioned in <a href="https://mail.mozilla.org/pipermail/es4-discuss/2008-March/002552.html">a posting to the ES4-Discuss list</a> yesterday that the proposal was dropped at the committee meeting last Friday:
</p>
<p>"...(news flash) proper tail calls are out of ES4 as of yesterday's Ecma TC39 meeting, by general (regretful, in Mozilla's case) agreement."
</p>
<p>
It's not in the meeting notes yet, but I'm sure it will be added before the meeting notes are finalized. I guess the writing was on the wall, because the only three companies that have commented on this feature have all marked this feature as a low priority in the <a href="http://spreadsheets.google.com/pub?key=pFIHldY_CkszsFxMkQOReAQ&gid=2">ES4 Progress Tracking Spreadsheet</a>.]]>
        
    </content>
</entry>
<entry>
    <title>ECMAScript 4 Edition Progress Spreadsheet</title>
    <link rel="alternate" type="text/html" href="http://blogs.adobe.com/fcheng/2008/03/ecmascript_4_edition_progress.html" />
    <link rel="service.edit" type="application/atom+xml" href="http://blogs.adobe.com/cgi-bin/mt-atom.cgi/weblog/blog_id=193/entry_id=5270" title="ECMAScript 4 Edition Progress Spreadsheet" />
    <id>tag:blogs.adobe.com,2008:/fcheng//193.5270</id>
    
    <published>2008-03-12T18:35:33Z</published>
    <updated>2008-03-12T18:45:25Z</updated>
    
    <summary>John Resig, Mozilla&apos;s JavaScript Evangelist and creator of jQuery, has created a spreadsheet to track the progress of the various implementations of ECMAScript 4th Edition. There are about a half-dozen implementations in development, including the reference implementation that the ECMAScript...</summary>
    <author>
        <name>Francis Cheng</name>
        <uri>http://blogs.adobe.com/fcheng</uri>
    </author>
            <category term="ECMAScript" />
    
    <content type="html" xml:lang="en" xml:base="http://blogs.adobe.com/fcheng/">
        <![CDATA[<p>John Resig, Mozilla's JavaScript Evangelist and creator of jQuery, has created <a href="http://spreadsheets.google.com/pub?key=pFIHldY_CkszsFxMkQOReAQ&gid=2">a spreadsheet to track the progress of the various implementations of ECMAScript 4th Edition</a>. There are about a half-dozen implementations in development, including the reference implementation that the ECMAScript working group is developing. Here's a brief description of the implementations so that you know what's what when you take a gander at the spreadsheet:
</p>

]]>
        <![CDATA[<ul>
  <li><strong><a href="http://www.ecmascript.org/download.php">ES4 RI</a></strong>: This is the ECMAScript 4th Edition reference implementation that the ES4 working group is developing. It is written in Standard ML '97, except for the library of core classes, which is written in ES4 itself.</li>
  <li><strong><a href="http://www.mozilla.org/projects/tamarin/">Tamarin</a></strong>: This began life as the AVM2 (ActionScript Virtual Machine 2), but morphed into Tamarin when the AVM2 was released as open source and handed over to Mozilla for hosting and coordination. Tamarin will serve as the VM for future versions of Flash Player as well as future versions of the FireFox web browser.</li>
  <li><strong><a href="http://www.mozilla.org/js/spidermonkey/">Spidermonkey</a></strong>: This is a JavaScript engine hosted by Mozilla. It provides scripting support in many applications, some of which are Mozilla FireFox, Yahoo! Widgets, Adobe Acrobat, and Adobe Flash CS3 (allows scripting control of the Flash authoring tool with JSFL).</li>
  <li><strong><a href="http://www.mozilla.org/rhino/">Rhino</a></strong>: This is another Mozilla JavaScript engine, but this one is written entirely in Java and is intended for use in applications rather than in browsers.</li>
  <li><strong>Futhark</strong>: This is a JavaScript engine developed by Opera Software for use in Opera's browser versions 9.5 and 10.0. </li>
  <li><strong><a href="http://www.mbedthis.com">Mbedthis</a></strong>: Mbedthis specializes in embedded web server solutions and is developing EJScript 3.0, which is based on ES4.</li>
  <li><strong>JSCore</strong>: This is short for JavaScriptCore, which is the JavaScript engine in <a href="http://webkit.org">WebKit</a>.</li>
</ul>

<p>
Yet another set of columns in the spreadsheet indicates the current thinking of several companies that participate in the ES4 working group. It uses color coding to indicate whether a particular feature is high or low priority for a given company. So far, Adobe, Google, Mozilla and Mbedthis have filled out these columns. Apple has indicated that they will have their column filled out by the end of the week. These columns are not binding in any way, but will be used to inform further discussions about the various proposals.
</p>

<p>
Here's the link to the ES4 progress spreadsheet again, in case you missed it at the top of the post:
</p>
<ul>
  <li><a href="http://spreadsheets.google.com/pub?key=pFIHldY_CkszsFxMkQOReAQ&gid=2">http://spreadsheets.google.com/pub?key=pFIHldY_CkszsFxMkQOReAQ&gid=2</a></li>
</ul>]]>
    </content>
</entry>
<entry>
    <title>Proposed ... (splat) operator in ECMAScript 4th Edition allows easy pass-through of rest arguments to super constructor. </title>
    <link rel="alternate" type="text/html" href="http://blogs.adobe.com/fcheng/2008/03/proposed_splat_operator_in_ecm.html" />
    <link rel="service.edit" type="application/atom+xml" href="http://blogs.adobe.com/cgi-bin/mt-atom.cgi/weblog/blog_id=193/entry_id=5356" title="Proposed ... (splat) operator in ECMAScript 4th Edition allows easy pass-through of rest arguments to super constructor. " />
    <id>tag:blogs.adobe.com,2008:/fcheng//193.5356</id>
    
    <published>2008-03-07T22:01:19Z</published>
    <updated>2008-03-07T22:02:01Z</updated>
    
    <summary> Recently, Brendan Eich added a new trac ticket that proposes a new operator, ... (informally called &quot;splat&quot;), for ECMAScript 4th edition. The fate of this ticket is currently unknown, but I really like this proposal because it solves a...</summary>
    <author>
        <name>Francis Cheng</name>
        <uri>http://blogs.adobe.com/fcheng</uri>
    </author>
            <category term="ActionScript" />
            <category term="ECMAScript" />
    
    <content type="html" xml:lang="en" xml:base="http://blogs.adobe.com/fcheng/">
        <![CDATA[<p>
Recently, Brendan Eich added <a href="http://bugs.ecmascript.org/ticket/357">a new trac ticket</a> that proposes a new operator, <code>...</code> (informally called "splat"), for ECMAScript 4th edition. The fate of this ticket is currently unknown, but I really like this proposal because it solves a thorny issue I've had when trying to pass ...rest arguments to a super constructor in ActionScript 3.0. I'll get back to that problem in a minute, but first I want to draw a clear distinction between the proposed <code>...</code> (splat) operator and the </code>...</code> (rest) parameter that many of you have probably used in ActionScript 3.0.
</p>]]>
        <![CDATA[<p>
In case you don't know, ActionScript 3.0 has a <code>...</code> (rest) parameter that you can use to specify that a function accepts a variable number of arguments. For example, the Array.push() method uses the rest parameter to signify that it accepts a comma-separated list of arguments:
</p>

<textarea cols=65 rows=2 READONLY>
AS3 function push(... args):uint {}
</textarea>

<p>
The <code>...</code> (splat) operator complements the rest parameter by allowing you to send an array of values as arguments to a function when you don't know ahead of time what the length of that array will be at runtime. In other words, you use the rest parameter when you define what a function will accept as arguments and you use the splat operator when you are actually sending arguments during a function call. Now let's take a quick look at the major use case that the splat operator addresses.
</p>

<p>
Let's say you have a base class with a constructor that uses a rest parameter. You then create a subclass with a constructor that also uses a rest parameter. How do you pass the arguments from the subclass's constructor to the superclass's constructor? Let's see what happens when we do that:
</p>
<textarea cols=80 rows=15 READONLY>
class Base {
	public function Base (... args) { 
		trace ("1st element of args:" + args[0]); // trace only 1st element
	}
}

class Extender extends Base {
	public function Extender (... args) { 
		super(args);
	}
}

var bs:Base = new Base(1, 2, 3);         // 1st element of args: 1
var ex:Extender = new Extender(1, 2, 3); // 1st element of args: 1, 2, 3
</textarea>
<p>
Note that in the constructor for Base, I trace only the first element of the args array. When I create an instance of Base and pass in the list of numbers <code>1, 2, 3</code>, the constructor converts the arguments into an array of three elements. However, when I create an instance of Extender with that same list of numbers, they end up bunched together as an array in the first element of the args array in the Base constructor. Unfortunately, in ActionScript 3.0 you cannot use Function.apply() to call the super constructor. There is currently no simple way in ActionScript 3.0 to pass through the arguments to the super constructor and have the arguments treated the same way whether they come from a direct instantiation of Base or through a call to <code>super()</code> from Extender. 
</p>
<p>
The proposed <code>...</code> (splat) operator solves this problem by allowing simple pass-through of rest arguments using the following new syntax:
</p>
<textarea cols=80 rows=6 READONLY>
class Extender extends Base {
	public function Extender (... args) : super(... args) { 
	    // no need to call super() in the constructor body
	}
}
</textarea>

<p>
Here's a list of relevant links:
</p>
<ul>
  <li><a href="http://livedocs.adobe.com/flash/9.0/ActionScriptLangRefV3/statements.html#..._(rest)_parameter">The ... (rest) parameter entry in the ActionScript 3.0 Language Reference</a></li>
  <li><a href="http://bugs.ecmascript.org/ticket/357">Trac ticket #357: Add ... (splat) operator to complement rest params and support new/apply composition</a></li>
  <li><a href="https://mail.mozilla.org/pipermail/es4-discuss/2008-March/002150.html">Recent thread on ES4-Discuss list about this issue</a></li>
</ul>
]]>
    </content>
</entry>
<entry>
    <title>ECMAScript 4th Edition Vectors Proposal Draft 1</title>
    <link rel="alternate" type="text/html" href="http://blogs.adobe.com/fcheng/2008/03/ecmascript_4th_edition_vectors_1.html" />
    <link rel="service.edit" type="application/atom+xml" href="http://blogs.adobe.com/cgi-bin/mt-atom.cgi/weblog/blog_id=193/entry_id=5269" title="ECMAScript 4th Edition Vectors Proposal Draft 1" />
    <id>tag:blogs.adobe.com,2008:/fcheng//193.5269</id>
    
    <published>2008-03-04T02:44:43Z</published>
    <updated>2008-03-04T06:17:12Z</updated>
    
    <summary>Lars T. Hansen, a computer scientist here at Adobe and the editor of the ECMAScript 4th Edition Specification, has written an initial rough draft of the Vectors proposal. The entire draft is reproduced below from his post on the ES4-Discuss...</summary>
    <author>
        <name>Francis Cheng</name>
        <uri>http://blogs.adobe.com/fcheng</uri>
    </author>
            <category term="ECMAScript" />
    
    <content type="html" xml:lang="en" xml:base="http://blogs.adobe.com/fcheng/">
        <![CDATA[Lars T. Hansen, a computer scientist here at Adobe and the editor of the ECMAScript 4th Edition Specification, has written an initial rough draft of the Vectors proposal. The entire draft is reproduced below from <a href="https://mail.mozilla.org/pipermail/es4-discuss/2008-March/002065.html">his post on the ES4-Discuss list</a>. I'm reproducing it in its entirety because the discussion list archive converts the file such that you see the raw HTML, which can be a little hard to read. If you have comments, please join the <a href="https://mail.mozilla.org/listinfo/es4-discuss">ES4-Discuss list</a> and join in the conversation. Comments on this blog are always welcome, but to get the attention of the ES4 decision makers, you need to join the ES4-discuss list and post your comments there.  Here's the link to the draft proposal:

<ul>
  <li><a href="http://blogs.adobe.com/fcheng/ecma/vector_draft_1.html">Vector class ECMAScript 4th Edition Proposal, Draft 1</a></li>
</ul>]]>
        

    </content>
</entry>
<entry>
    <title>Type Parameters in ECMAScript 4th Edition</title>
    <link rel="alternate" type="text/html" href="http://blogs.adobe.com/fcheng/2008/02/type_parameters_in_ecmascript.html" />
    <link rel="service.edit" type="application/atom+xml" href="http://blogs.adobe.com/cgi-bin/mt-atom.cgi/weblog/blog_id=193/entry_id=5243" title="Type Parameters in ECMAScript 4th Edition" />
    <id>tag:blogs.adobe.com,2008:/fcheng//193.5243</id>
    
    <published>2008-02-29T05:30:17Z</published>
    <updated>2008-03-07T00:55:55Z</updated>
    
    <summary> The ECMAScript 4th Edition draft specification includes something called type parameters, also known as parameterized types or generics. This feature is useful for adding type checking to collection classes. For example, let&apos;s say you have a List class that...</summary>
    <author>
        <name>Francis Cheng</name>
        <uri>http://blogs.adobe.com/fcheng</uri>
    </author>
            <category term="ActionScript" />
    
    <content type="html" xml:lang="en" xml:base="http://blogs.adobe.com/fcheng/">
        <![CDATA[<p>
The ECMAScript 4th Edition draft specification includes something called type parameters, also known as parameterized types or generics. This feature is useful for adding type checking to collection classes. For example, let's say you have a List class that you have customized to your liking.
</p>]]>
        <![CDATA[<textarea cols=65 rows=3 READONLY>
class List {
  ...
}
</textarea>
<p>
You like it so much, in fact, that you use it in many different situations. The only problem is that in ActionScript 3.0, you can't easily use strong typing to specify that a specific instance of List should contain only a certain data type. You could extend List, I supppose, and create a ListOfIntegers class, a ListOfStrings class, etc., but that can get hard to manage if you use it for more than just a few different types.
</p>
<p>
The type parameters feature, however, makes strong typing of collections much easier. If you saw <a href="http://blogs.adobe.com/fcheng/2008/02/vectors.html">my previous post about Vectors</a>, you've already seen type parameters in action because the Vector class requires them. But let's rewrite the List class using a type parameter:
</p>
<textarea cols=65 rows=4 READONLY>
class List.<T> {
  private var head:T;
  ...
}
</textarea>
<p>
What we've done is define List such that it is now a "list of some type", where the type is represented by the parameter "T". In other words, the class List.&lt;T&gt; is "generic" in the sense that it is not tied down to a specific data type, at least until you specify a type when you create an instance of the class. This means that we can use the parameter "T" inside our class definition as if it were a type. You can see in the declaration of the variable <code>head</code> that we used a type annotation of "T". When we later create an instance of the List.&lt;T&gt; class, the compiler will substitute the type we specify for every occurrence of "T". 
</p>
<p>
Let's say I have a class called Employee and I want to create an instance of my List class that stores only instances of the Employee class. Here's what it would look like:
</p>
<textarea cols=65 rows=2 READONLY>
var EmpList:List.<Employee> = new List.<Employee>();
</textarea>

<p>
So you're probably wondering what's up with the funny syntax for type parameters. How did we end up with the syntax <code>className.&lt;Type&gt;</code> for type parameters? Well, the working group went through a long discussion about it, which you can read on the <a href="http://wiki.ecmascript.org/doku.php?id=discussion:type_parameters#the_bracket_issue">type parameters proposal discussion page</a> at the ecmascript.org site.
</p>

<h3>ES4 Type Parameters are Unbounded</h3>

<p>
One thing you may have noticed about the List.&lt;T&gt; class is that T can be any type. We passed in the type "Employee", but we could have passed in <code>int</code>, <code>string</code>, or any other built-in or custom type. There's no way in ES4 to limit, or in other words create bounds for, the types that you can pass in to for "T". Some languages with generics allow you to constrain the type parameter by setting up type boundaries. In other words, some languages allow you to specify a restricted set of types that can be used as typed arguments. For example, in Java you can define a class that takes a type parameter that must extend another class, so you could say <code>class List&lt;T extends Employee&gt;</code>, to get a List class that takes only subclasses of Employee. The ES4 spec does not require implementations to provide bounded type parameters.
</p>


<h3>ES4 Type Parameters are Invariant</h3>
<p>
Best way to explain this is through an example. Let's take that Employee class we talked about earlier and extend it with a new subclass called TechWriter. Clearly, TechWriter is a subclass of Employee, and can be safely used anywhere that Employee is used. But does that mean that List.&lt;TechWriter&gt; is a subtype of List.&lt;Employee&gt;? It turns out the answer is no. The ramifications of this can be seen in the following example, in which the function <code>reprimand()</code> takes a parameterized List as its parameter:
</p>

<textarea cols=65 rows=3 READONLY>
function reprimand(list:List.<Employee>) { ... }
var writingTeam:List.<TechWriter> = new List.<TechWriter>();
reprimand(writingTeam); // error because ES4 type parameters are invariant
</textarea>

<p>
Calling the <code>reprimand()</code> function with a value of type List.&lt;TechWriter&gt; causes an error because the function is expecting the type List.&lt;Employee&gt;. Other languages use something called variance annotations to solve this problem. In this case, the error would go away if the subtype relationship of the two lists matched the subtype relationship of the types Employee and TechWriter. Such variance is called <em>covariance</em>. Java, for example, allows you to use wildcards to indicate that you want to allow covariance, something like <code>&lt;? extends Employee&gt;</code> would do it if you used that in the declaration of <code>reprimand()</code>.
</p>
<p>
The type parameters proposal does leave open the possibility that variance annotations could be added in a later edition of ECMAScript. The proposal points to a <a href="http://www.sato.kuis.kyoto-u.ac.jp/~igarashi/papers/variance.html">journal article</a> that proposes a variance annotation style that is simpler than Java's. If ECMAScript goes that route, you would be able to rewrite the function to support covariant type parameters with just one extra symbol (note the + symbol in the declaration of <code>reprimand()</code>):
</p>
<textarea cols=70 rows=4 READONLY>
// Not legal in ES4
function reprimand(list:List.<+Employee>) { ... }
var writingTeam:List.<TechWriter> = new List.<TechWriter>();
reprimand(writingTeam); // no error if variance annotation is added in ES5
</textarea>

<p>
Personally, I like the brevity of this style of variance annotation and hope that they adopt this for ECMAScript 5. The proposal lists a workaround, however, that purportedly mitigates the need for variance annotations. I have to say, though, that the proposed alternative is little intense for my taste, but hey, I'm just a tech writer. You can have a look at it and see if you like it better than using a variance annotation. Look for the code example that defines a class called Container.&lt;T&gt; on the type parameters proposal page under the <a href="http://wiki.ecmascript.org/doku.php?id=proposals:type_parameters#variance_roadmap">section titled Variance Roadmap</a>.
</p>

<p>
Here are some useful links I came across in researching type parameters. These deal mostly with generics in Java, C++ and C#:
</p>
<ul>
<li><a href="http://wiki.ecmascript.org/doku.php?id=proposals:type_parameters">Type Parameters Proposal on ecmascript.org</a></li>
<li><a href="http://www.angelikalanger.com/GenericsFAQ/JavaGenericsFAQ.html\">Java Generics FAQ</a></li>
<li><a href="http://java.sun.com/developer/technicalArticles/J2SE/generics/">Using and Programming Generics in J2SE 5.0, by Qusay H. Mahmoud</a></li>
<li><a href="http://java.sun.com/j2se/1.5/pdf/generics-tutorial.pdf">Generics in the Java Programming Language, by Gilad Bracha (PDF)</a></li>
<li><a href="http://msdn.microsoft.com/msdnmag/issues/05/04/PureC/">Generic Programming Under .NET, by Stanley B. Lippman</a></li>
<li><a href="http://www.artima.com/intv/generics.html">Generics in C#, Java, and C++, A Conversation with Anders Hejlsberg, Part VII, by Bill Venners with Bruce Eckel</a></li>
<li><a href="http://webservices.sys-con.com/read/39935.htm">Optimizing Web Services Using Java, Part I - Generic Java and Web services, By Jordan Anastasiade</a></li>
</ul>]]>
    </content>
</entry>
<entry>
    <title>ECMAScript 4th edition Reference Implementation M2</title>
    <link rel="alternate" type="text/html" href="http://blogs.adobe.com/fcheng/2008/02/ecmascript_4th_edition_referen.html" />
    <link rel="service.edit" type="application/atom+xml" href="http://blogs.adobe.com/cgi-bin/mt-atom.cgi/weblog/blog_id=193/entry_id=5121" title="ECMAScript 4th edition Reference Implementation M2" />
    <id>tag:blogs.adobe.com,2008:/fcheng//193.5121</id>
    
    <published>2008-02-19T19:49:09Z</published>
    <updated>2008-02-19T20:00:05Z</updated>
    
    <summary>Last week the ES4 working group released a new version of the ES4 reference implementation (RI). The new build, M2 (for Milestone 2), replaces the M1 build that was posted back in November 2007. Today, one of the most active...</summary>
    <author>
        <name>Francis Cheng</name>
        <uri>http://blogs.adobe.com/fcheng</uri>
    </author>
            <category term="ECMAScript" />
    
    <content type="html" xml:lang="en" xml:base="http://blogs.adobe.com/fcheng/">
        <![CDATA[<p>Last week the ES4 working group released a new version of the ES4 reference implementation (RI). The new build, M2 (for Milestone 2), replaces the M1 build that was posted back in November 2007. Today, one of the most active implementors of the RI, Graydon Hoare of Mozilla, posted a detailed "punch list" of all the proposed features that are either included or not included in the latest version of the RI.</p>
]]>
        <![CDATA[<p>Here's a little background about the RI for those of you who haven't been following the progress of the ES4 working group. Most of the working group members found the pseudo-code used in the ES3 specification hard to work with in that it was both hard to get the specification correct and hard to implement. As pseudocode, it was also hard to identify bugs. Not wishing to propogate these same problems into the next edition of the specification, the working group decided to create an reference implementation that serves several purposes. First, it provides an initial proof of concept that the new edition of the language can indeed be implemented. Second, it provides a much more precise way to specify what the language is supposed to do. Third, it makes it much easier to identify bugs in the specification.</p>

<p>After considering a few languages, the working group settled on Standard ML '97 and use a compiler/programming environment called <a href="http://www.smlnj.org/">Standard ML of New Jersey</a>, or SML/NJ for short. That need not concern you, however, if you just want to play around with some of the new features because Dave Herman has created a set of binaries for Windows, Mac OSX and Linux that you can download from the <a href="http://www.ecmascript.org/download.php">ecmascript.org downloads area</a>.</p>

<p>Here is Graydon's punch list of features that are in the "M2" build of the RI (from his <a href="https://mail.mozilla.org/pipermail/es4-discuss/2008-February/001912.html">original post to ES4-Discuss</a>):</p>

<p>Implemented, may have bugs:</p>

 <ul>  <li>classes and interfaces
  </li><li>namespaces
  </li><li>pragmas
  </li><li>let, const, let-const
  </li><li>iterators
  </li><li>enumerability control
  </li><li>type expressions / definitions / annotations
  </li><li>runtime type checks ("standard mode")
  </li><li>nullability
  </li><li>destructuring assignment
  </li><li>slice syntax
  </li><li>hashcode
  </li><li>catchalls
  </li><li>map & vector
  </li><li>date & time improvements
  </li><li>meta objects
  </li><li>static generics
  </li><li>string trim
  </li><li>typeof
  </li><li>globals
  </li><li>expression closures
  </li><li>name objects
  </li><li>type operators (is / to / cast / wrap)</li>
  </ul>
<p>Implemented and partly working, but still in flux / work to do:</p>
<ul>
  <li>inheritance checking
  </li><li>strict mode
  </li><li>type parameters
  </li><li>structural types
  </li><li>numbers & decimal
  </li><li>getters & setters (structural part is incomplete)
  </li><li>packages</li>
</ul>
<p>Partially implemented / not yet working:</p>
<ul>
  <li>program units
  </li><li>generic function
  </li><li>updates to unicode
  </li><li>updates to regexps</li>
</ul>
<p>Unimplemented:</p>
<ul>
  <li>generators
  </li><li>tail calls
  </li><li>triple quotes
  </li><li>stack inspection
  </li><li>reformed with
  </li><li>resurrected eval (eval exists but may be wrong)
  </li><li>help for the argument object
  </li><li>"this function" / "this generator"</li>
</ul>
<p>
In case you missed it above, here is a link to the downloads area of the ecmascript.org site if you want to download binary versions of the RI (The source code is also available on that page):
</p>
<ul><li><a href="http://www.ecmascript.org/download.php">ecmascript.org downloads area</a>.</li></ul>]]>
    </content>
</entry>
<entry>
    <title>Vectors in ECMAScript 4</title>
    <link rel="alternate" type="text/html" href="http://blogs.adobe.com/fcheng/2008/02/vectors.html" />
    <link rel="service.edit" type="application/atom+xml" href="http://blogs.adobe.com/cgi-bin/mt-atom.cgi/weblog/blog_id=193/entry_id=5077" title="Vectors in ECMAScript 4" />
    <id>tag:blogs.adobe.com,2008:/fcheng//193.5077</id>
    
    <published>2008-02-13T22:13:28Z</published>
    <updated>2008-02-13T22:16:06Z</updated>
    
    <summary>A new built-in class named Vector is proposed for ECMAScript edition 4. This class is similar to the Array class, but is designed for better performance, efficiency and error checking. Some interesting aspects of the Vector class: vectors are dense;...</summary>
    <author>
        <name>Francis Cheng</name>
        <uri>http://blogs.adobe.com/fcheng</uri>
    </author>
            <category term="ActionScript" />
            <category term="ECMAScript" />
    
    <content type="html" xml:lang="en" xml:base="http://blogs.adobe.com/fcheng/">
        <![CDATA[<p>A new built-in class named Vector is proposed for ECMAScript edition 4. This class is similar to the Array class, but is designed for better performance, efficiency and error checking. Some interesting aspects of the Vector class:</p>

<ul>
  <li>vectors are dense;</li>
  <li>vectors do bounds checking;</li>
  <li>vectors can be fixed length;</li>
  <li>vectors have type parameters;</li>
  <li>vectors have the same methods as arrays.</li>
</ul>

]]>
        <![CDATA[<p>I'll take a closer look at each of these bullet points, but first, here's how the Vector class and constructor declaration will probably look in ActionScript, where 'T' represents a data type:</p>

<textarea cols=65 rows=5 READONLY>
final class Vector.<T> {

    function Vector(length:uint=0, fixed:boolean=false) {}
    ....
}
</textarea>

<p>The Vector class is is defined with the <code>final</code> attribute right now, which means that you cannot create subclasses. This could change, however, before the specification is finalized. The <code>length</code> parameter has a type annotation of <code>uint</code>, which means that the maximum vector size is <code>2<sup>32</sup>-1</code> and the largest index value you can use is <code>2<sup>32</sup>-2</code>. 
</p>

<h3>Vectors are dense</h3>
<p>
If you are familiar with ActionScript arrays, you know that they can have "holes" in them. For example, let's say you have an array that has three elements and the length property is 3. That's a "dense" array with no holes. However, I can write to an arbitrary index number and the array will automatically "grow" to accommodate me. For example, if I write to index 10, the length of the array will grow to 11, but the array will have a hole in it between index 3 and 9, inclusive. Or, you could look at it as having 7 holes, with each undefined element considered a hole. Having holes like this can really slow down the process of iterating through the array. Vectors, by contrast, are always dense. You cannot have holes in a vector. Every element of a vector is always defined.
</p>

<h3>Vectors do bounds checking</h3>
<p>
So what happens if I have a vector with three elements and I try to assign a value to index 10, as I did with an array in the previous paragraph? The short answer is that you get a runtime error (a RangeError to be precise). In fact, this happens even you just try to read from that index, much less write to that index. 
</p>
<p>
There is a little flexibility built in, however, for those who want to change the size of the vector. First, you can "grow" a vector by assigning to the very next available index. For example, if I have a vector with three elements (index positions 0, 1, and 2), I can directly assign a fourth element to index position 3. Second, I can alter the value of the <code>length</code> property to grow or shrink the size of the vector. For example, if I change the <code>length</code> to 11, I'll increase the size of my vector so that it contains 11 elements. This is somewhat similar to how the <code>length</code> property works for arrays, but the significant difference is that with vectors, all 11 of the elements are defined. Both of these techniques, however, work only if the <code>fixed</code> property is set to <code>false</code>.
</p>

<h3>Vectors can be fixed length</h3>
<p>
You may have noticed that the second parameter to the Vector constructor function is a boolean named <code>fixed</code>. The default value is <code>false</code>, but you can set this to <code>true</code> either at construction time or anytime thereafter using the <code>fixed</code> property of the Vector class. Whenever <code>fixed</code> is set to true, any attempt to change the size of the vector will generate a runtime error, whether the attempt is made by assigning a value to the index number that is equal to the value of <code>length</code> or by directly changing the value of the <code>length</code> property.
</p>

<h3>Vectors have type parameters</h3>
<p>
You can use type parameters to designate that you want a "mono-typed" vector, which means that the vector can contain values of only one specific type. For example, you can define a vector that holds only integers and has a fixed length of 7 by declaring:
</p>
<textarea cols=65 rows=2 READONLY>
var intVector:Vector.<int> = new Vector.<int>(7, true)
</textarea>
<p>
The resulting <code>intVector</code> vector will be constrained to values of type <code>int</code>.
</p>

<h3>Vectors have the same methods as Arrays</h3>
<p>
The current plan is for the Vector class to have as many of the Array methods as possible. Vector will contain not only the traditional methods such as <code>push()</code>, <code>pop()</code>, <code>slice()</code>, <code>sort()</code>, etc., but also some of the newer methods such as <code>every()</code>, <code>filter()</code>, <code>indexOf()</code>, <code>some()</code>, etc. A complete list should be available soon on ecmascript.org.
</p>
<p>
This only scratches the surface of the new Vector class. Rest assured that there will be more to come about this new built-in class as we move forward with the draft specification. Here are some relevant links on the ecmascript.org site:
</p>
<ul>
  <li><a href="http://wiki.ecmascript.org/doku.php?id=proposals:vector">Vectors proposal on the ecmascript.org wiki</a></li>
  <li><a href="http://bugs.ecmascript.org/ticket/234">Open Trac issue that discusses whether Vector will be final (see comments)</a></li>
  <li>You can download an <a href="http://www.ecmascript.org/download.php">early version of the ES4 reference implementation</a> and play with the Vector class.</li>
</ul>]]>
    </content>
</entry>
<entry>
    <title>Logical Assignment Operators</title>
    <link rel="alternate" type="text/html" href="http://blogs.adobe.com/fcheng/2008/02/logical_assignment_operators.html" />
    <link rel="service.edit" type="application/atom+xml" href="http://blogs.adobe.com/cgi-bin/mt-atom.cgi/weblog/blog_id=193/entry_id=5034" title="Logical Assignment Operators" />
    <id>tag:blogs.adobe.com,2008:/fcheng//193.5034</id>
    
    <published>2008-02-07T18:30:29Z</published>
    <updated>2008-02-09T00:23:27Z</updated>
    
    <summary>Thought I&apos;d switch gears this week and talk about Logical Assignment Operators (||=, &amp;&amp;=), a feature that is proposed for ECMAScript 4th edition, but is already implemented in ActionScript 3.0. To understand the rationale behind the Logical Assignment Operators, you...</summary>
    <author>
        <name>Francis Cheng</name>
        <uri>http://blogs.adobe.com/fcheng</uri>
    </author>
            <category term="ActionScript" />
            <category term="ECMAScript" />
    
    <content type="html" xml:lang="en" xml:base="http://blogs.adobe.com/fcheng/">
        <![CDATA[<p>Thought I'd switch gears this week and talk about Logical Assignment Operators (<code>||=</code>, <code>&&=</code>), a feature that is proposed for ECMAScript 4th edition, but is already implemented in ActionScript 3.0. To understand the rationale behind the Logical Assignment Operators, you need to understand how the logical operators in ECMAScript and ActionScript work. Most people think of these operators in purely boolean terms. In other words, if you have two boolean variables, <code>conditionA</code> and <code>conditionB</code>, you can use the logical operators to calculate logical results. For example, if one condition is <code>true</code> and the other is <code>false</code>, the logical AND operator returns a value of <code>false</code> because both conditions have to be <code>true</code> in order for logical AND to return <code>true</code>. ]]>
        <![CDATA[The logical OR operator, on the other hand, returns <code>true</code> in this case because it takes only one condition to be <code>true</code> for the logical OR operator to return <code>true</code>:</p>

<textarea cols=65 rows=5 READONLY>
var conditionA:Boolean = true;
var conditionB:Boolean = false;

var bothTrue:Boolean = conditionA && conditionB;    // false
var atLeastOneTrue:Boolean = conditionA || conditionB; // true
</textarea>

<p>The logical operators are far more interesting than this, however, in that they are not limited to Boolean values. You can use other values as operands to the logical operators. For example, let's say you want to check whether values have been assigned to a pair of string variables. The result is <code>true</code> only if both variables contain string values.</p>
<code>
<textarea cols=65 rows=15 READONLY>
var str1:String;
var str2:String;

var bothStringsSet:Boolean = str1 && str2;  
trace (bothStringsSet);  // false

str1 = "foo";

bothStringsSet = str1 && str2;  
trace (bothStringsSet);  // false

str2 = "bar";

bothStringsSet = str1 && str2;  
trace (bothStringsSet);  // true
</textarea>
</code>

<p>But it gets even more interesting because the logical operators don't necessarily return a Boolean value. What's really going on is that the logical operator returns the value of one operand or the other. For example, the logical AND operator examines the first operand and if that operand is either <code>false</code> or can be converted to <code>false</code>, the operator returns the first operand and never even looks at the second operand. If the first operand turns out to be <code>true</code>, the second operand is returned. We can see this in action if we just change the type annotation of the variable <code>bothStringsSet</code> in the previous example to type String:</p>

<textarea cols=65 rows=5 READONLY>
var str1:String;
var str2:String;

var bothStringsSet:String = str1 && str2;  
trace (bothStringsSet);  // null
</textarea>
<p>This is <code>null</code> because the value of the first operand, <code>str1</code>,  converts to <code>false</code>, so the logical AND operator returns the value of <code>str1</code>, which is <code>null</code></p>

<textarea cols=65 rows=4 READONLY>
str1 = "foo";

bothStringsSet = str1 && str2;  
trace (bothStringsSet);  // null
</textarea>
<p>This is also <code>null</code> because even though the value of the first operand now converts to <code>true</code>, this just means that the logical AND operator returns the value of the second operand, <code>str2</code>, which is still <code>null</code>.</p>

<textarea cols=65 rows=4 READONLY>
str2 = "bar";

bothStringsSet = str1 && str2;  
trace (bothStringsSet);  // bar
</textarea>
<p>The logical AND operator does the same thing here as it did in the previous code snippet--it returns the value of the second operand because <code>str1</code> converts to <code>true</code>, but we get a different value as a result because the second operand now has the value <code>bar</code>. That's not a very practical example, so let's look at something that makes a little more sense. </p>

<p>Many programmers use the logical OR operator to assign default values. The logical OR operator is the exact opposite of the logical AND operator. In other words, the logical OR operator returns the first operand if it is either <code>true</code> or can be converted to <code>true</code>, and otherwise returns the second operand. What does this have to do with assigning default values? Well, you only want to assign a default value if a variable is undefined, so you could write the following code to assign a default value:</p>

<textarea cols=65 rows=7 READONLY>
var myVar:String;

if (myVar == undefined) {
	myVar = "default";
}

trace(myVar);  // default
</textarea>

<p>Alternatively, you could use the logical OR operator to serve the same purpose:</p>

<textarea cols=65 rows=5 READONLY>
var myVar:String;

myVar = myVar || "default";

trace(myVar);  // default
</textarea>

<p>If <code>myVar</code> is undefined, the logical OR operator considers that as <code>false</code>, so it returns the value of the second operand, <code>"default"</code>. If <code>myVar</code> has a value assigned already, the logical OR operator considers that as <code>true</code> and just re-assigns the value of <code>myVar</code> to <code>myVar</code>. It's a matter of personal taste. Some argue that using the <code>if</code> statement is easier to read. Nevertheless, there are some programs that use the logical operator technique, so at the very least it's handy to know about it.</p>

<p>Finally, we get to the "assignment" part of the logical assignment operators. For those of you who find the logical OR technique for assigning default values distasteful because it's hard to read, you may want to stop reading now. I say this because a common technique among Ruby and Perl programmers is to use an even more abbreviated form of this technique that takes advantage of the logical OR assignment operator. In other words, the following code:</p>

<textarea cols=65 rows=1 READONLY>
myVar = myVar || "default";
</textarea>

<p>can be rewritten using the logical OR assignment operator:</p>

<textarea cols=65 rows=1 READONLY>
myVar ||= "default";
</textarea>

<p>There you have what I believe to be the most common use of the logical OR assignment operator. Examples of the logical AND assignment operator are less common, but one use-case could be to increment a variable, but only when that variable is greater than zero. For example, the following code increments <code>myNum</code> only if it is not zero:</p>
<textarea cols=65 rows=3 READONLY>
var myNum:int;
myNum &&= ++myNum;
trace(myNum);
</textarea>

<p>As parting words, I should say that I'm not advocating the use of this technique, but I do think it's worth understanding because you may come across code that uses this technique.</p>]]>
    </content>
</entry>
<entry>
    <title>Proper Tail Calls and State Machines</title>
    <link rel="alternate" type="text/html" href="http://blogs.adobe.com/fcheng/2008/02/proper_tail_calls_and_state_ma.html" />
    <link rel="service.edit" type="application/atom+xml" href="http://blogs.adobe.com/cgi-bin/mt-atom.cgi/weblog/blog_id=193/entry_id=4996" title="Proper Tail Calls and State Machines" />
    <id>tag:blogs.adobe.com,2008:/fcheng//193.4996</id>
    
    <published>2008-02-01T17:16:07Z</published>
    <updated>2008-02-01T18:18:36Z</updated>
    
    <summary>It turns out that Proper Tail Calls (PTC) are handy if you want to create a simple &quot;state machine&quot; or &quot;finite state machine&quot;. A state machine is a way to create a model for the way an object behaves. For example, let&apos;s create a state machine model for a United States traffic light. </summary>
    <author>
        <name>Francis Cheng</name>
        <uri>http://blogs.adobe.com/fcheng</uri>
    </author>
            <category term="ActionScript" />
            <category term="ECMAScript" />
    
    <content type="html" xml:lang="en" xml:base="http://blogs.adobe.com/fcheng/">
        <![CDATA[<p>It turns out that Proper Tail Calls (PTC) are handy if you want to create a simple "state machine" or "finite state machine" (See my <a href="http://blogs.adobe.com/fcheng/2008/01/proper_tail_calls_a_definition.html">previous post</a> if you don't know what PTC is). A state machine is a way to create a model for the way an object behaves. For example, let's create a state machine model for a United States traffic light. First I'll use a design pattern to create one, then I'll show you a completely different approach using PTC. Here are the components of the model:<p>

<ul>
  <li>Finite number of states. There are three states in our example: red, yellow, and green.</li>
  <li>Input. This is an event-driven model, so the input is an event that signifies a light change.</li>
  <li>Finite number of transitions. There are three transitions in our example: red to green, green to yellow, and yellow to red.</li>
</ul>
]]>
        <![CDATA[<p>
There are many different ways to implement a state machine. You can use a series of if/else statements or a switch clause that controls the transitions from state to state, but that approach doesn't scale well. Instead, we'll use the state design pattern, originally presented by Gamma, et. al. in their famous <a href="http://en.wikipedia.org/wiki/Design_Patterns">"Design Patterns"</a> book. </p>

<h4>Traffic Light Using the State Pattern</h4>
<p>First we start with a class that Gamma calls the "context", which in our case is a class I'll call TrafficLight. This class is sort of the "master" class that we'll use to represent the state machine. Second, we'll create an interface, let's call it IState, that contains methods that represent all the behaviors in our state machine. Well, in our case there's only one behavior, which is <code>changeColor()</code>. Third, we'll implement this interface with classes that represent each of our states. We'll have three classes: RedLight, YellowLight, and GreenLight, all of which will implement the IState interface.</p>

<p>For simplicity's sake, I'm just making my variables public and I'm ignoring the need for event listeners and a timer. Also, I'm including only the RedLight class because the YellowLight and GreenLight classes are essentially the same:</p>

<p><b>TrafficLight Class</b></p>
<textarea cols=65 rows=22 READONLY>
public class TrafficLight extends Sprite
{
	public var redLight:IState;
	public var yellowLight:IState;
	public var greenLight:IState;
	
	private var state:IState = redLight;
	
	public function TrafficLight()
	{
		redLight = new RedLight(this);
		yellowLight = new YellowLight(this);
		greenLight = new GreenLight(this);

	}
	
	public function changeColor(newState:IState):void
	{
		state = newState;
	}
}
</textarea>
<p><b>IState Interface</b></p>
<textarea cols=65 rows=4 READONLY>
public interface IState
{
	function changeColor():void;
}
</textarea>
<p><b>RedLight Class</b></p>
<textarea cols=65 rows=12 READONLY>
public class RedLight implements IState
{
	private var _light:TrafficLight;
	
	public function RedLight(light:TrafficLight) {
		_light = light;
	}
	
	public function changeColor() :void	{
		_light.changeColor(_light.greenLight);
	}
}
</textarea>

<p>That's a lot of structure for a simple model, but the payoff is that you have a model that's easy to extend. For example, we could easily adapt this state machine to handle British traffic lights that have an extra state where red and yellow both appear. All it would take is a new RedYellowLight class and minor changes to the TrafficLight and RedLight classes. Now let's take a different approach that uses PTC.</p>

<h4>Traffic Light with PTC</h4>
<p>When I mean different, I mean that we'll leave the nicely structured world of class-based programming and enter the wild world of dynamic programming. So turn off Strict mode and let's not worry about type annotations. If we have PTC at our disposal, we can use it to design a quick and easy state machine that uses a function to represent each state. It can't get much simpler than that. When it is time to transition to a new state we make a tail call to the appropriate function.</p>

<textarea cols=65 rows=22 READONLY>
var cycles = 250;

function redLight () {
	trace("RED");
	cycles--;
	if (cycles == 0) {
		return;
	}
	return greenLight();
}

function yellowLight() {
	trace("YELLOW");
	return redLight();
}

function greenLight() {
	trace("GREEN");
	return yellowLight();
}

redLight();
</textarea>

<p>I added a variable named <code>cycles</code> to control the number of times the program runs. What's interesting is that if I set <code>cycles</code> to anything over 252, I get a stack overflow error. I'm only decrementing in the redLight function, so that means each decrement of <code>cycles</code> represents three functions placed on the stack. So the error appears after a little more 750 of those functions are placed onto the stack. Clearly, you wouldn't want to use this technique in ActionScript today, but if PTC becomes part of ActionScript, the stack overflow error would not occur because each tail call function would replace the preceding call on the stack. Of course, this is not necessarily a better way to implement a state machine, but it is an alternative that certainly has an appealing simplicity to it. It may not scale as well as the design pattern technique, but may come in handy for implementing simple games.</p>

<p>Here are some links to resources about state machines:</p>

<ul>
  <li><a href="http://www.lua.org/pil/6.3.html">6.3 Proper Tail Calls</a>, from Programming in Lua, by Roberto Ierusalimschy</li>
  <li><a href="http://www.ibm.com/developerworks/library/wa-finitemach1/">Finite State Machines in JavaScript</a>, by Edward J. Pring</li>
  <li><a href="http://en.wikipedia.org/wiki/Finite_state_machine">Finite State Machine, Wikipedia Article</a></li>
  <li><a href="http://www.bigroom.co.uk/blog/finite-state-machines-for-ai-in-actionscript">Finite State Machines for AI in ActionScript</a></li>
  <li><a href="http://www.adobe.com/devnet/flashmediaserver/articles/video_state_machine_as3.html">Creating a video player using the state design pattern and ActionScript 3.0</a>, by Bill Sanders.</li>
</ul>]]>
    </content>
</entry>
<entry>
    <title>Proper Tail Calls and Recursion</title>
    <link rel="alternate" type="text/html" href="http://blogs.adobe.com/fcheng/2008/01/proper_tail_calls_and_recursio.html" />
    <link rel="service.edit" type="application/atom+xml" href="http://blogs.adobe.com/cgi-bin/mt-atom.cgi/weblog/blog_id=193/entry_id=4979" title="Proper Tail Calls and Recursion" />
    <id>tag:blogs.adobe.com,2008:/fcheng//193.4979</id>
    
    <published>2008-01-30T19:13:54Z</published>
    <updated>2008-02-01T18:52:21Z</updated>
    
    <summary>Today I&apos;m going to talk about the proposed Proper Tail Calls (PTC) feature and recursion.  I&apos;m going to show you how PTC can significantly reduce stack usage for functions with recursive calls in tail position.</summary>
    <author>
        <name>Francis Cheng</name>
        <uri>http://blogs.adobe.com/fcheng</uri>
    </author>
            <category term="ActionScript" />
            <category term="ECMAScript" />
    
    <content type="html" xml:lang="en" xml:base="http://blogs.adobe.com/fcheng/">
        <![CDATA[<p>Today I'm going to talk about the proposed Proper Tail Calls (PTC) feature and recursion.  I'm going to show you how PTC can significantly reduce stack usage for functions with recursive calls in tail position. If you recall, I mentioned in <a href="http://blogs.adobe.com/fcheng/2008/01/proper_tail_calls_a_definition.html">my previous post</a> that Proper Tail Calls is also called Proper Tail Recursion. This is because PTC has a significant effect on certain types of recursive functions. In case you're unfamiliar with recursion, a recursive function is a function that calls itself. For example, we could use a recursive function to calculate the factorial of a number, which means multiplying a number by every integer between that number and zero, as in 3! = 3 x 2 x 1 = 6. ]]>
        <![CDATA[Here's an ActionScript function that calculates factorials:</p>

<textarea cols=65 rows=8 READONLY>
function factorial (num:int): Number {
	if (num <= 1) {
		return 1;
	}
	else {
		return num * factorial(num-1);
	}
}
</textarea>

<p>So let's call <code>factorial()</code> with an argument of 3 and walk through the code execution. The parameter <code>num</code> is assigned a value of 3, which means we skip down to the <code>else{}</code> statement because 3 is greater than 1. In the <code>else{}</code> statement, we call <code>factorial()</code> again, but this time with the argument value 2. When the new call happens, the runtime suspends execution of the original call to <code>factorial()</code> and pushes the original call onto the stack because we'll need it later. Next, we walk through the second call to <code>factorial()</code>, but with the value 2. We get similar results, <code>factorial()</code> gets called a third time, but this time with an argument value of 1. </p>

<p>At this point we've not yet returned from any function, so all of these functions are still active and piled onto the stack, with our initial call at the bottom of the stack. With the call to <code>factorial(1)</code>, however, we finally enter the <code>if{}</code> statement and simply return the value 1. This means that the call to <code>factorial(1)</code> can be discarded and we emerge back inside the <code>else{}</code> statement in the previous call to the factorial function, <code>factorial(2)</code>. This return trip back down the stack is where values are returned and the calculations occur:</p>

<textarea cols=65 rows=4 READONLY>
factorial(1) returns the value 1 
factorial(2) returns the value 2 * 1
factorial(3) returns the value 3 * 2
</textarea>

<p>Notice that the recursive call to <code>factorial()</code> is not in tail position because the last thing the function does is multiply <code>num</code> by the return value of <code>factorial(num-1)</code>. So PTC would not affect the execution of <code>factorial()</code> as it is written above. To get the benefits of PTC, we would need to refactor the code so that the recursive call to <code>factorial()</code> is in tail position. One way to do that would be to use a helper function that handles the recursion:</p>

<textarea cols=80 rows=14 READONLY>
function factorialEx (num:int):Number {
	return factorialIterator(1, 1, num); 
}

function factorialIterator(counter:int, subTotal:Number, maxCount:int) {
	if (counter == maxCount) {
		return subTotal * counter;
	}
	else {
		return factorialIterator (counter + 1,
					  subTotal * counter,
					  maxCount)
	}
}
</textarea>

<p>PTC will apply to <code>factorialIterator()</code> because the recursive call to <code>factorialIterator()</code> is in tail position. The <code>factorialEx()</code> function takes a very different approach in that it uses a counter to track progress so that it doesn't have to fill up the stack with a large number of suspended function calls. A call to <code>factorialEx()</code> sets in motion a series of tail calls that keeps stack usage constant. Stepping through, a call to <code>factorialEx(3)</code> results in a tail call to <code>factorialIterator()</code>, which results in recursive tail calls until the counter is equal to 3. The <code>subTotal</code> parameter stores the running total throughout this process.</p>

<p>The difference between these two techniques is more pronounced if you consider larger factorials. If you want to calculate 40 factorial, the original <code>factorial()</code> function will result in extensive stack usage that will require memory enough to hold 40 deferred function calls. On the other hand, if PTC is added to the language, the <code>factorialEx()</code> function will grow the stack by no more than one function. Currently, however, ActionScript exhibits the same extensive stack-usage behavior for both <code>factorial()</code> and <code>factorialEx()</code>.</p>

<p>You may be thinking that 40 or so functions on the stack are not a big deal, and we can't feed numbers to <code>factorial()</code> much bigger than that before we exceed the capacity of the Number type to hold the answer. I agree that this isn't a great example of the benefit of PTC, but it was useful as a simple way to explain the differences between these recursive functions. There are other examples, such as calculating Fibonacci numbers, that better show the benefits of PTC.  You could write a non-tail-recursive Fibonacci function that calls itself for every addition operation. There you would run into ActionScript's recursion limit when feeding in numbers that call for more than a thousand calculations. That would mean a thousand suspended functions stored on the stack, which would contrast sharply with a tail-recursive implementation that would grow the stack by exactly one function.</p>

<p> Here are links to some of the materials I used in my research for this post:
<ul>
   <li><a href="http://mitpress.mit.edu/sicp/">Structure and Interpretation of Computer Programs</a></li>
   <li><a href="http://www.tratt.net/laurie/tech_articles/articles/tail_call_optimization">Tail Call Optimization, by Laurence Tratt</a></li>
   <li><a href="http://home.in.tum.de/~baueran/thesis/">Compilation of Functional Programming Languages using GCC - Tail Calls (pp. 7 - 9), by Andreas Bauer</a></li>
   <li><a href="http://www.ccs.neu.edu/home/will/papers.html">Proper tail recursion and space efficiency, by William Clinger</a></li>
    <li><a href="http://wiki.ecmascript.org/doku.php?id=proposals:proper_tail_calls">Proper Tail Calls, ECMAScript 4th Edition proposal</a></li>
</ul>
</p>]]>
    </content>
</entry>
<entry>
    <title>Proper Tail Calls, a definition</title>
    <link rel="alternate" type="text/html" href="http://blogs.adobe.com/fcheng/2008/01/proper_tail_calls_a_definition.html" />
    <link rel="service.edit" type="application/atom+xml" href="http://blogs.adobe.com/cgi-bin/mt-atom.cgi/weblog/blog_id=193/entry_id=4970" title="Proper Tail Calls, a definition" />
    <id>tag:blogs.adobe.com,2008:/fcheng//193.4970</id>
    
    <published>2008-01-29T05:51:39Z</published>
    <updated>2008-01-29T06:29:01Z</updated>
    
    <summary>Today I&apos;ll start with a definition of Proper Tail Calls (PTC). The essence of PTC is that it provides a new way to return from a function. Namely, instead of returning a value, you can call any other function as the last thing you do. </summary>
    <author>
        <name>Francis Cheng</name>
        <uri>http://blogs.adobe.com/fcheng</uri>
    </author>
            <category term="ActionScript" />
            <category term="ECMAScript" />
    
    <content type="html" xml:lang="en" xml:base="http://blogs.adobe.com/fcheng/">
        <![CDATA[<p>One of the things I get to do here at Adobe is help out with the drafting of the ECMAScript Edition 4 (ES4) language specification. Lately, there has been a flurry of discussion on the ES4-discuss list about one of the proposed new features, Proper Tail Calls (a.k.a. Proper Tail Recursion, but I'm going to call it PTC from now on). I thought this might give me a good opportunity to provide some background information about this feature and what it might mean for ActionScript developers in the future.</p>

<p>In case you don't know, ECMAScript is the language standard upon which JavaScript, JScript, ActionScript and many other languages are based. The current version of ECMAScript is the third edition, but a lot of work is going on for the fourth edition. So what I'm discussing here is not currently in ActionScript, but may one day be if PTC makes it into the fourth edition specification.</p>]]>
        <![CDATA[<p>Today I'll start with a definition of PTC, and I'll follow up over the next few days with examples and further thoughts. You can find the <a href="http://wiki.ecmascript.org/doku.php?id=proposals:proper_tail_calls">ES4 proper tail calls proposal</a> at the ecmascript.org website. I should warn you, though, that the proposals are geared more toward language implementors than users, so don't worry too much if you don't understand all the terminology they use. I'll try in this blog to translate what some of these proposals mean for ActionScript developers.</p>

<p>Speaking of writing geared toward computer scientists, the best definition of PTC I've come across is from a journal article by William Clinger at Northeastern University titled "Proper Tail Recursion and Space Efficiency". In that paper, he talks about the essence of PTC, which I'll paraphrase in terms of ActionScript below. I have to admit that much of the article is over my head, but he writes clearly so I learned a lot from reading the sections that I could wrap my brain around. He has the article posted on his website if you're interested in further reading (<a href="http://www.ccs.neu.edu/home/will/papers.html">http://www.ccs.neu.edu/home/will/papers.html</a>).</p>

<p>According to Professor Clinger, the essence of PTC is that it provides a new way to return from a function. Namely, instead of returning a value, you can call any other function as the last thing you do. Such a function call is said to be in tail position, or to make things easier you can just refer to the call as a "tail call". This may not seem like a big deal, but it does add a new twist to the life cycle of a function.</p>

<p>Consider a typical ActionScript function:</p>

<pre>function foo () {
   trace("hello");
}</pre>

<p>The foo() function will exist in memory from the time that you call it to the time that it returns from that call. The runtime (I'm going to use the word "runtime" instead of "Flash Player" or "Virtual Machine") will store the function in a special area of memory called the stack. As the name implies, a stack is organized as a last-in first-out stack, like a deck of playing cards that grows and shrinks as you add, use, and discard cards from the top of the deck. Notice in our example that we call another function, trace(), from the body of foo(). This means that foo() remains in memory while the trace() function runs. In terms of the stack, the runtime stores trace() on top of foo(). This is not a big issue in our little example, but what if it turns out that trace() calls another function, and that function calls another function, and so on. Pretty soon your stack starts getting pretty big. In fact, sometimes your stack can get too large and you get a stack overflow error.</p>

<p>PTC changes this behavior if the function call is in tail position. Instead of keeping foo() in the stack and placing trace() on top of it, foo() is discarded and trace() takes its place. This seems like a sensible thing to do because foo() doesn't do anything after the call to trace(), so why keep it around in memory? (Some argue that keeping it around is really helpful for debugging, but we'll talk about that another day.) And if there's a tail call in trace(), that call replaces trace() in the stack and so on. Instead of an ever-growing stack, you get a stack that may not grow at all, which will make a stack overflow exception much less likely.</p>

<p>PTC's ability to increase stack-use efficiency leads some people to call this feature Tail Call Optimization (TCO). However, the motivation section of the ES4 proposal for PTC states:</p>

<p>"Proper tail calls are not an optimization, but an aspect of the semantics of the space usage of the language."</p>

<p>I hope that Professor Clinger's insight into the essence of PTC helps you see this as more than just a mere optimization. If you don't, it may be because I did a poor job of paraphrasing him, so I would encourage you to read his article. Over the next few days I'll post new entries that delve more deeply into PTC. Specifically, I'll devote separate posts to recursion and how PTC is useful for programming with finite state machines.</p>]]>
    </content>
</entry>

</feed> 

