<?xml version="1.0" encoding="UTF-8"?>
<!--Generated by Squarespace Site Server v5.9.2 (http://www.squarespace.com/) on Fri, 12 Mar 2010 16:53:59 GMT--><feed xmlns="http://www.w3.org/2005/Atom" xmlns:dc="http://purl.org/dc/elements/1.1/"><title>Mascara: ECMAScript 6 -&gt; JavaScript translator</title><subtitle>News</subtitle><id>http://blog.mascaraengine.com/news/</id><link rel="alternate" type="application/xhtml+xml" href="http://blog.mascaraengine.com/news/"/><link rel="self" type="application/atom+xml" href="http://blog.mascaraengine.com/news/atom.xml"/><updated>2010-02-06T17:35:45Z</updated><generator uri="http://www.squarespace.com/" version="Squarespace Site Server v5.9.2 (http://www.squarespace.com/)">Squarespace</generator><entry><title>"If a feature is not documented, it does not exist"</title><id>http://blog.mascaraengine.com/news/2010/2/6/if-a-feature-is-not-documented-it-does-not-exist.html</id><link rel="alternate" type="text/html" href="http://blog.mascaraengine.com/news/2010/2/6/if-a-feature-is-not-documented-it-does-not-exist.html"/><author><name>Olav</name></author><published>2010-02-06T17:31:23Z</published><updated>2010-02-06T17:31:23Z</updated><content type="html" xml:lang="en-US"><![CDATA[<p>The documentation for Mascara is not yet completely perfect, but now at least we have a <a href="http://www.mascaraengine.com/doc/keywords">list of keywords</a>!</p>]]></content></entry><entry><title>Code completion</title><id>http://blog.mascaraengine.com/news/2010/1/18/code-completion.html</id><link rel="alternate" type="text/html" href="http://blog.mascaraengine.com/news/2010/1/18/code-completion.html"/><author><name>Olav</name></author><published>2010-01-18T22:17:15Z</published><updated>2010-01-18T22:17:15Z</updated><content type="html" xml:lang="en-US"><![CDATA[<p>A major advantage of statically typed languages is support for<strong> code completion</strong>. Code completion is the editor-feature where the editor suggest relevant names (variable names, method names etc.) based on what is defined and allowed in the current context - as you type. This has the potential to greatly enhance productivity. For example, you dont have to look up method names in the source or in documentation, but can just type a dot and see what methods are defined for the current object. This also helps prevent typos in identifiers.</p>
<p>As a proof-of-concept I have implemented code completion in the online "try-it" editor <a href="http://www.mascaraengine.com">over here</a>. Of course the online editor is not suited for serious use, but it does provide a nice showcase for what is possible.</p>
<p><span class="full-image-float-left ssNonEditable"><span><img src="http://blog.mascaraengine.com/storage/magic.png?__SQUARESPACE_CACHEVERSION=1263853076964" alt="" /></span></span> Code completion is disabled in the editor by default. It is enabled by clicking the "magic wand" icon leftmost in the toolbar. (The suggestions may be somewhat slow to appear, since the editor has to hit the server to get the suggestions.)</p>
<p>An example of how it looks when i start writing the letter "f":</p>
<p><span class="full-image-block ssNonEditable"><span><img src="http://blog.mascaraengine.com/storage/suggestions.png?__SQUARESPACE_CACHEVERSION=1263854015101" alt="" /></span></span></p>
<p>You can cycle through the suggestions using the up/down arrow keys. A suggestion is selected by hitting enter, or clicking it with the mouse.</p>
<p>The suggestion box appears automatically when you start typing, or it can be forced to show by pressing control+space.</p>
<p>A limitition in the current implementation is that the autocompletion usually wont work if there is compilation errors in the code. We are working on that issue.</p>
<p>A related experimental feature is support for documentation comments. If a variable or function is preceeded by a comment starting with <strong>/**</strong> (note: two stars rather than the usual one), the content of that comment is displayed as help related to the suggestion for the function. As in this example:</p>
<p><span class="full-image-block ssNonEditable"><span><img src="http://blog.mascaraengine.com/storage/doc.png?__SQUARESPACE_CACHEVERSION=1263854546198" alt="" /></span></span></p>
<p>(Tags like what is known from doc-comments is Java or C# is not supported yet, though.)</p>
<p>Any feedback welcome!</p>]]></content></entry><entry><title>Parser error at or near '{'</title><id>http://blog.mascaraengine.com/news/2009/9/14/parser-error-at-or-near-1.html</id><link rel="alternate" type="text/html" href="http://blog.mascaraengine.com/news/2009/9/14/parser-error-at-or-near-1.html"/><author><name>Olav</name></author><published>2009-09-14T07:30:33Z</published><updated>2009-09-14T07:30:33Z</updated><content type="html" xml:lang="en-US"><![CDATA[<p>Useful and detailed error messages have always been a priority in the design of Mascara. I believe good error messages means a lot for the day-to-day productivity when using a language tool such as this.</p>
<p>Therefore it has always been a bit embarassing with the generic "Parser error at or near..." message in the case of syntax errors.</p>
<p>It just tells you that some character is wrong, not what you are supposed to write instead. Especially when learning a new language this can be infuriating. Particularily for people (like me!) who like to explore by trial and error.</p>
<p>In the latest Mascara release, parser error messages have been improved so they now suggest what syntax would be allowed instead of the erroneous character.</p>
<p>E.g. if you write</p>
<pre class="prettyprint">class {}</pre>
<p>You get:</p>
<p><strong>Syntax error. Unexpected '{'. Expected identifier</strong></p>
<p>This tells you that an identifier is required after the keyword "class", which is hopefully a lot more useful than just the message "<strong>Parser error at or near '{'</strong>".</p>
<p>In many cases multiple options are legal at a given point. If you write:</p>
<pre class="prettyprint">class A()<br /></pre>
<p>The compiler will report:</p>
<p><strong>Syntax error. Unexpected '('. Expected one of: '!', 'implements', 'extends', '.<', ';', '{'.</strong></p>
<p>That is quite a number of tokens to choose from, but hopefully it gives a much better hint about how to fix the syntax error.</p>
<p>Sometimes it can be slightliy less obvious where the actual error is. Consider this:</p>
<pre class="prettyprint">var x =<br />var y = 100;<br /></pre>
<p>In this example I forgot to finish the first line. However the compiler will flag the "var" on the <em>second </em>line with "<strong>Unexpected var. Expected expression.</strong>" This is because it would be legal to have the assignment value on the next line - but then "var" is not a legal expression, which causes an error.</p>
<p>In general it is a difficult problem to give helpful error messages for syntax errors, but hopefully these improvements is a step in the right direction, and will make it more fun to explore the language by trial and error.</p>]]></content></entry><entry><title>Access modifiers in Mascara</title><id>http://blog.mascaraengine.com/news/2009/9/10/access-modifiers-in-mascara.html</id><link rel="alternate" type="text/html" href="http://blog.mascaraengine.com/news/2009/9/10/access-modifiers-in-mascara.html"/><author><name>Olav</name></author><published>2009-09-10T21:39:24Z</published><updated>2009-09-10T21:39:24Z</updated><content type="html" xml:lang="en-US"><![CDATA[<p>Access modifiers (<strong>private </strong>and <strong>public</strong>) are among the most frequently requested features. They are now supported in the latest Mascara version, 1.2.4 (<a href="http://www.mascaraengine.com/download">Download</a>).</p>
<p>A private member is accessible only by methods in the same class. A public member is accessibly by everyone, just as members always are in classic JavaScript.</p>
<pre class="prettyprint">class A {<br />&nbsp;&nbsp;&nbsp; public function famous() {};<br />&nbsp;&nbsp;&nbsp; private function secret() {};<br />&nbsp;&nbsp;&nbsp; private function test() {<br />&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; famous();&nbsp; //OK because famous is public&nbsp; <br />         secret(); //OK because we are members of the same class<br />&nbsp;&nbsp;&nbsp; }<br />}<br />var a = new A();<br />a. famous(); //OK<br />a. secret(); //ERROR, secret is not accessible from here<br /></pre>
<p>Members are public by default.</p>
<p>Static members can also be private. Private static methods can access private instance members in the same class and vice versa.</p>
<p>Constructors can also be private. With a private constructor it is not possible for other classes to create instances of the class. Static methods on the same class are then used to instantiate and return instances of the class. This can be used to implement patterns like singleton and factory.</p>
<p>Have fun with encapsulation!</p>]]></content></entry><entry><title>Python 2.6 builds</title><id>http://blog.mascaraengine.com/news/2009/9/2/python-26-builds.html</id><link rel="alternate" type="text/html" href="http://blog.mascaraengine.com/news/2009/9/2/python-26-builds.html"/><author><name>Olav</name></author><published>2009-09-02T11:06:12Z</published><updated>2009-09-02T11:06:12Z</updated><content type="html" xml:lang="en-US"><![CDATA[<p>Mascara is now availably built for Python 2.6 (the latest, recommended version of Python). Versions built for Python 2.5 is still available. If you dont know which Python version you have, you most probably have Python 2.6.</p>
<p><a href="http://www.mascaraengine.com/download">Download here</a>.</p>]]></content></entry><entry><title>Getters and setters</title><id>http://blog.mascaraengine.com/news/2009/8/23/getters-and-setters.html</id><link rel="alternate" type="text/html" href="http://blog.mascaraengine.com/news/2009/8/23/getters-and-setters.html"/><author><name>Olav</name></author><published>2009-08-23T17:36:29Z</published><updated>2009-08-23T17:36:29Z</updated><content type="html" xml:lang="en-US"><![CDATA[<p>Mascara has supported <strong>getter </strong>and <strong>setter </strong>functions and methods for some time, but in anticipation of the forthcoming ECMAScript 5 standard it has now added support for getters and setters in object literals.</p>
<p><span>In short, getters and setters are special functions which are invoked the same way a variable or property is read or assigned.</span></p>
<p><span>Here is an example of a <strong>getter</strong>:</span></p>
<pre class="prettyprint"><p><span>//defining a getter function x<br />function get x() { return 7; }<br />// the function is invoked by accessing the variable value:<br />var a = x;  // (a is assigned the result of calling get x, i.e. 7)</span></p></pre>
<p><span>This is pretty useful for  encapsulating member access.&nbsp; A <strong>setter </strong>is the corresponding function which emulates assigning a value to a property or variable:</span></p>
<pre class="prettyprint"><p><span>function set x(x) { alert(x) }<br />x = &ldquo;hello&rdquo;; // set x is invoked and shows </span><span>an alert box with &ldquo;hello&rdquo;</span></p></pre>
<p><span>Getters and setters (together known as &ldquo;accessors&rdquo;) are useful for various forms of encapsulation. For example we can perform validation on input, we can change the internal representation without changing the interface, or we can trigger events when a property is changed.</span></p>
<p><span>Getters and setters often appear together, but we can emulate read-only properties by only providing a getter, or (less commonly) write-only properties by just exposing a setter.</span></p>
<p>The new addition is that ECMAScript 5 defines a syntax for gettes and setters in object literals.<span> Example:</span></p>
<pre class="prettyprint"><p><span>var ecoStorage = { <br /></span><span>    // to save memory space we only save half the value</span><span>    <br />    _storage : 0.0, <br />    get x() { return ecoStorage._storage * 2; },<span> </span><br />    set x(value) { ecoStorage._storage = value / 2 }</span><span><br />};<br />ecoStorage.x = 100;</span><span><br />var y = ecoStorage.x;</span><span style="font-family: Wingdings;"><span> //</span></span><span> y is assigned 100</span></p></pre>
<p><span>So the accessors appear in the place of a <em>name:value</em> pair in an object literal.</span></p>
<p><span>Above we get a single object instance with the getter/setter pair. If we want to instiate multiple object, we have to create a constructor the object literal as a prototype. Hence:</span></p>
<pre class="prettyprint"><p><span>function EcoStorage() {}</span><span><br />EcoStorage.prototype = {<br />    _storage : 0, </span><br />    get x() { return this._storage * 2; }, <span><br />    set x(value) { this._storage = value / 2 }</span><span><br />};</span><span><br />var storage1 = new EcoStorage;</span><span><br />storage1.x = 100;<br />var y = storage1.x; // y is assigned the value 100</span></p></pre>
<p><span>This approach is also supported in Mascara, however I can&rsquo;t say I find the syntax particularity attractive. I appreciate the flexibility declaring prototypes explicitly, but the syntax is not elegant.</span></p>
<p><span>The idiomatic way to do the same in Mascara is to use classes:</span></p>
<pre class="prettyprint"><p>class EcoStorage {<br />    var _storage : double = 0;<br />    function get x() { return _storage * 2; }<br />    function set x(value) { _storage = value / 2; }</p><p>}<br />var s = new EcoStorage;<br />s.x = 100;</p></pre>
<p><span>Note the slightly different syntax (<strong>function get</strong> instead of just <strong>get</strong>) for getters/setter when they appear outside of object literals.</span></p>
<p>The ECMAScript 5 spec <em>only </em>allows getters and setters in object literals. However there is a low-level way to defining getters and setters through the new <em>Object.defineProperty()</em> method. This requires support in the JavaScript engine and is therefore not available in Mascara. It is not necessaray either, since Mascara supports the more straightforward syntax shown above.</p>
<p><span>Getters/setters in classes and as stand-alone functions has been supported in Mascara for a while. The ES5 compliant syntax for getters/setters in object literals is new in Mascara 1.2</span></p>
<p><span>Have fun!<br /></span></p>]]></content></entry><entry><title>Mascara 1.2 - With interfaces</title><id>http://blog.mascaraengine.com/news/2009/8/19/mascara-12-with-interfaces.html</id><link rel="alternate" type="text/html" href="http://blog.mascaraengine.com/news/2009/8/19/mascara-12-with-interfaces.html"/><author><name>Olav</name></author><published>2009-08-19T13:52:42Z</published><updated>2009-08-19T13:52:42Z</updated><content type="html" xml:lang="en-US"><![CDATA[<p><a href="http://www.mascaraengine.com/download">Mascara 1.2 has been released</a>, and supports <em>interfaces</em>, an often requested feature.</p>
<p>They work as you would expect very much like interfaces in Java and C#. Basically they describe a set of methods that any class that implements the interface must provide implementations for.</p>
<p>Interfaces may contain function and getter/setter declarations, but not variables or nested types. (Hence ECMAScript interfaces does not allow constants as in Java). Declaration are just function signatures without a body.</p>
<p>Example:</p>
<pre class="prettyprint"><p>interface Moveable {<br />&nbsp; function moveTo(x: int, y:int) : void;<br />}</p><p>class DialogBox implements Moveable {<br />&nbsp;&nbsp;&nbsp; function moveTo(x : int, y:int) : void {<br />        // implementation<br />    }<br />}</p></pre>
<p>Interfaces can inherit from multiple other interfaces, and classes can implement multiple interfaces.</p>
<p>Syntax is defined in the <a href="http://www.mascaraengine.com/doc/interface">documentation</a>.</p>]]></content></entry><entry><title>Arrays and higher-order functions in the type system</title><id>http://blog.mascaraengine.com/news/2009/8/9/arrays-and-higher-order-functions-in-the-type-system.html</id><link rel="alternate" type="text/html" href="http://blog.mascaraengine.com/news/2009/8/9/arrays-and-higher-order-functions-in-the-type-system.html"/><author><name>Olav</name></author><published>2009-08-09T15:39:00Z</published><updated>2009-08-09T15:39:00Z</updated><content type="html" xml:lang="en-US"><![CDATA[<p>Lets look closer at how types are handled in Mascara in relation to Arrays and higher-order functions.  This provides  an interesting view into the type system.</p>
<p>Since this is not a general introduction to parameterized types, it is probably best understood if you already knows parameterized types, e.g. from Java or C# (where they are called "generics", but otherwise looks a lot the same.)</p>
<p>An Array can by default contain values of any type. However, an array can also be instantiated with a type parameter:</p>
<pre class="prettyprint lang-js">var x = new Array.&lt;int&gt;</pre>
<p>This creates a new array which may only contain integer values.<br />If you initialize with an array literal like this:</p>
<pre class="prettyprint lang-js">var x = [1,2,3]</pre>
<p>The compiler will determine the Array type from the initial values. In this case it will assume an array if integers, ie. Array.&lt;int&gt;, because all of the items are integers.</p>
<p>The Array class is declared like this:</p>
<pre class="prettyprint">dynamic class Array.&lt;T&gt; { ... methods ... }</pre>
<p>The T is the type parameter which represent the type of the items. when a new array is constructed, the type parameter T is initialized with a concrete type.</p>
<p>Usually the compiler requires you to explicitly provide type arguments. However Array is special-cased (for backwards compatibility), so that when it is initialized without a type argument, it defaults to use the &ldquo;star&rdquo; type argument, which is the "anything goes" type.</p>
<p>Hence <tt class="prettyprint">new Array</tt> gets translated into <tt class="prettyprint">new Array.&lt;*&gt;</tt>.</p>
<p>[Aside: <span style="font-weight:bold;">dynamic</span> is a modifier which indicates than any property can be attached to the object at runtime without the compiler complaining. This is supported for backwards compatibility]</p>
<p>Now let&rsquo;s look at the type signature for <span style="font-weight:bold;">every</span>:</p>
<pre class="prettyprint">function every(callbackfn:(function(item:T, ix:int):boolean)) : boolean {...}</pre>
<p>This signature may seem daunting because of the nested function signature. <span style="font-weight:bold;">every</span> takes one argument, <span style="font-weight:bold;">callbackfn </span>which is in turn a function which takes two arguments.</p>
<p>The first argument to the callback function is a list item, hence its type is T, the type parameter for the Array. Hence if the list is a list of ints, the function has to take an int as the first argument.</p>
<p>The second argument to the callback is the index of the current item in the array. This is sometimes useful to have, but we may choose to ignore this argument as we have done in the examples above.</p>
<p>There is a certain amount of flexibility in what callback functions can be supplied. For example, as we have seen above, arguments can be ignored/left out. However we cannot supply a function with more required parameters than the signature expects.</p>
<p>The parameters may be more accepting than what is declared. For example we can provide a function which expects a double as the item type:</p>
<pre class="prettyprint">[1,2,3].every(function(x:double) x / 2 &gt; 2)</pre>
<p>This will work even though T is int, since int is a subset of double. (Technically parameters are said to be contravariant.) This is allows us to supply a function without type annotations on the parameters, which is pretty nice, especially for backwards compatibility.<br />The return value of the callback has to be a boolean as declared. However, in the above case the compiler can figure out on its own that the callback returns a boolean, because the result of a comparison is always a boolean.</p>
<p>Next, lets look at <span style="font-weight:bold;">filter</span>:</p>
<pre class="prettyprint">function filter(callbackfn:(function(item:T, ix:int):boolean)) : Array.&lt;T&gt; {...}</pre>
<p>The parameters for the callback function are the same as above. The result type is itself a parameterized type - the same as the original array. Recall that T is defined as a type parameter for Array.</p>
<p>Hence if you filter an array of stings, the result is always a new array of strings (although the resulting list may be empty, the type is still Array.).</p>
<p>Now the most complex of the function signatures, <span style="font-weight:bold;">map</span>:</p>
<pre class="prettyprint">function map.&lt;Q&gt;(callbackfn:(function(item:T, ix:int):Q)) : Array.&lt;Q&gt; { ... }</pre>
<p>Note that the function takes a type parameter, which must match the result type of the supplied function, and which also determines the type the resulting array.</p>
<p>Hence, an explicitly typed invication of <span style="font-weight:bold;">map</span>:</p>
<pre class="prettyprint">x.map.&lt;string&gt;(function(x)x.toString()) --&gt; results in an array of type Array.&lt;string&gt;<br />x.map.&lt;double&gt;(function(x) x*2) --&gt; results in an array of type Array.&lt;double&gt;<br /></pre>
<p>Obviously, if there is a mismatch between the type parameter and the return type of the function, you get a complaint from the compiler</p>
<pre class="prettyprint">x.map.&lt;int&gt;(function(x) x.toString()) --&gt; compiler whines!</pre>
<p>Now, here is the nice part: The type parameter to the function can be left out, since the compiler can infer the type from the type of the supplied function.</p>
<p>E.g.</p>
<pre class="prettyprint">x.map(function(x) x.toString()) --&gt; results in an array of type Array.&lt;string&gt;, no complaints from the compiler</pre>
<p>Of course the type argument makes it explicit what type you expect, and it may help catch type errors. On the other hand you save a bit of typing when calling the method by relying on the inference.</p>
<p>Again, this is a question of preference. I just like that you can write in a "typeless" manner, and then later turn it into more explicitly typed code.</p>
<p>As shown we can get pretty far in a type safe manner without specifying types explicitly. But consider this example:</p>
<pre class="prettyprint">[1,2,3].map(function(x) x*2)</pre>
<p>This function will return an array of doubles, not an array of integers which you might expect. The reason is that the parameter to the callback is not specified, so the compiler has to be cautious. Multiplication is only guaranteed to return a double (since we consider int a subset of double).</p>
<p>An even worse example:</p>
<pre class="prettyprint">[1,2,3].map(function(x) x+2)</pre>
<p>Here we get a compiler warning, because + can be used on anything, but has different meanings depending on the types of input.</p>
<p>Of course we can choose to ignore the warning. But it is better style to annotate the parameters:</p>
<pre class="prettyprint">[1,2,3].map(function(x:int) x+2)</pre>
<p>This results in an array of integers.</p>
<p>Now you may wonder why the compiler can't infer the types in this case, since it is pretty obvious for us that the function will only be called with integers. However in the general case, the compiler cannot infer the types of function parameters, since there in no general solution for that. (Future versions of Mascara might attempt to infer function parameter types, but I doubt it will be possible in all cases.)</p>
<p>Therefore the general advice is to at least type-annotate function parameters. Typically the compiler will then be able to figure out the rest (e.g. local variables and return value).</p>
<p>The flamewars have raged for decades between proponents of static and dynamic typing. My experience is that static and explicit typing is a drag when experimenting and prototyping, however the bigger and more complex a project becomes, the more valuable static analysis becomes. I really likes that Mascara allows you to begin with dynamic and implicit typing, and then gradually add static guarantees as you find it appropriate.</p>]]></content></entry><entry><title>Higher-order array methods</title><id>http://blog.mascaraengine.com/news/2009/8/7/higher-order-array-methods.html</id><link rel="alternate" type="text/html" href="http://blog.mascaraengine.com/news/2009/8/7/higher-order-array-methods.html"/><author><name>Olav</name></author><published>2009-08-07T19:56:00Z</published><updated>2009-08-07T19:56:00Z</updated><content type="html" xml:lang="en-US"><![CDATA[<p>A most welcome addition in ES5 is the new higher-order array-methods: <span style="font-weight: bold;">map</span>, <span style="font-weight: bold;">filter</span>, <span style="font-weight: bold;">reduce</span>, <span style="font-weight: bold;">some</span>, <span style="font-weight: bold;">every</span>, <span style="font-weight: bold;">forEach</span>, <span style="font-weight: bold;">reduce </span>and <span style="font-weight: bold;">reduceRight</span>. They have long been available in various JavaScript frameworks, but it is nice to have them as part of the core language. In relation to Mascara the really cool thing is how they integrate with the type system - but I'll get back to that.</p>
<p>A higher-order function (or method) is defined as a function which takes another function as one of the arguments. This is especially useful when working with arrays, since the supplied function can be executed on some or all items in the array.</p>
<h3><strong>map</strong></h3>
<p>map applies a function to every item in an array, and returns a new array with the results. Example:</p>
<pre class="prettyprint">var numbers = [1,2,3,4]<br />function double(x) {<br />  return x * 2;<br />}<br />numbers.map(double) --returns--&gt; [2,4,6,8]</pre>
<p>If you only use the supplied function in this context, you can also provide an anonymous function inline:</p>
<p>numbers.map(function(x) { return x * 2; })</p>
<p>In these cases the new shorthand-function syntax comes in handy:</p>
<p>If a function body is a single expression, the brackets and "return"-statement can be left out, like:</p>
<pre class="prettyprint">numbers.map(function(x) x * 2)</pre>
<p>This shorthand syntax is also known as a "expression closure" or "lambda".</p>
<h3><strong>filter</strong></h3>
<p>Filter filters a list by only returning the items for which a condition is true. The condition is checked by supplying a function which returns true or false for a given item:</p>
<pre class="prettyprint">numbers.filter(function(x) x&gt;2) --&gt; [3,4]</pre>
<p style="font-family: georgia;">While map and filter are quite useful tool, I want to point out that array comprehensions are a very cool "syntactic sugar" for mapping and filtering. This filter/map method chaining:</p>
<pre class="prettyprint">var x = [1,2,3,4,5].filter(function(x)x&lt;7).map(function(x)x*2)</pre>
<p>is equivalent to this array comprehension:</p>
<pre class="prettyprint">var x = [x*2 for each (x in [1,2,3,4,5]) if (x&lt;7)]</pre>
<p>Personally I find the array comprehension syntax more elegant, although that may be a matter of taste. One technical advantage of array comprehensions as implemented in Mascara is that they support not just Array-instances, but also collections like HTML node lists:</p>
<pre class="prettyprint">[e.value<br />for each (e in document.getElementsByTagName("INPUT"))<br />     if (e.type=="text")]</pre>
<h3><strong>some and every<br /></strong></h3>
<p><span style="font-weight: bold;">some </span>and <span style="font-weight: bold;">every </span>are related to <span style="font-weight: bold;">filter </span>since they also take functions that returns a boolean for an item.</p>
<p><span style="font-weight: bold;">some </span>returns true if the condition is true for <span style="font-style: italic;">at least one</span> item in the list, while <span style="font-weight: bold;">every </span>return true if the condition is true for <span style="font-style: italic;">all </span>items.</p>
<p>Example:</p>
<p style="font-family:courier new;"><span style="font-family:courier new;">numbers.some(function(x) x&gt;2) --&gt; true</span> <span style="font-family:georgia;">(because some of the values are greater than 2)</span></p>
<p style="font-family: courier new;">numbers.every(function(x) x&gt;2) --&gt; false <span style="font-family:georgia;">(because not all values are greater than 2)</span></p>
<p><strong>forEach </strong>simply executes a function for each item in the list. It doesn&rsquo;t return anything, so this is done for side-effects. E.g.</p>
<pre class="prettyprint">x.forEach(function(x) { alert(x); });</pre>
<p>Note that I am using a real function body here, not a shortcut. Since the function passed to forEach should not return anything, it is not appropriate to use an expression.</p>
<p>The forEach method is pretty similar to using the for-each loop:</p>
<pre class="prettyprint">for each (x in numbers) { alert(x); }</pre>
<p>Lastly we have <span style="font-weight: bold;">reduce </span>and its mirror-twin <span style="font-weight: bold;">reduceRight</span>. They are a bit tricky to explain. <span style="font-weight: bold;">reduce </span>takes a function and an initial value as arguments. It executes the provided function with the initial value and the first item as arguments. The result of this is used as input to execute the function on the next item, and so on. The result of executing the function on the last item is the result of the reduce.</p>
<p>For example, the product of all items in a list can be calculated like this:</p>
<pre class="prettyprint">x.reduce(function(product, item) product * item, 1) ----&gt; 24</pre>
<p>And the sum:</p>
<pre class="prettyprint">x.reduce(function(sum : int, item : int) sum + item, 0) ----&gt; 10</pre>
<p><span>(Aside: In the last example I provide type annotations to indicate that the parameters are integers. This is because + works on both numbers and strings, so I help the compiler by indicating that they will be numbers (and hence the result will always be numeric. This is not necessary with *, since * only works on numbers anyway)</span><span style="font-weight: bold;"><br /></span></p>
<p><span style="font-weight: bold;">reduceRight </span>is the same except it traverses the list backwards, i.e. it first executes the function on the last item, then the next-to last and so on.</p>
<p>To be honest I think <span style="font-weight: bold;">reduce </span>and <span style="font-weight: bold;">reduceRight </span>are somewhat confusing - especially with more complex operations than just summing. The same thing can always be achieved with an ordinary for-each loop, and - to me at least - in a more obvious way:</p>
<pre class="prettyprint">var sum = 0;<br />for each (var item in x) sum += x;</pre>
<p>However, your mileage may vary. If you have a background in functional programming, the reduces may seem more natural, since you avoid a mutable variable.</p>
<p>The library that implements the methods is only included in the generated code if some these methods are actually used. Generally Mascara attempt to create as lean code as possible, hence boilerplate is only included when it is necessary.</p>]]></content></entry><entry><title>Mascara 1.1 and ECMAScript 5</title><id>http://blog.mascaraengine.com/news/2009/8/7/mascara-11-and-ecmascript-5.html</id><link rel="alternate" type="text/html" href="http://blog.mascaraengine.com/news/2009/8/7/mascara-11-and-ecmascript-5.html"/><author><name>Olav</name></author><published>2009-08-07T11:22:00Z</published><updated>2009-08-07T11:22:00Z</updated><content type="html" xml:lang="en-US"><![CDATA[<p>Mascara version 1.1 has been released. New in this release is support for a number of features from ECMAScript 5.</p><p>The <a href="http://www.ecma-international.org/publications/files/drafts/tc39-2009-025.pdf">ECMAScript 5 spec</a> (PDF link) is the latest spec released by the ECMA group. It is in "candidate draft" stage, which means that it is more or less final, but it awaits experience from implementations.</p><p>It may seem curious that ECMA releases an ECMAScript <span style="font-weight: bold;">5</span> version when there haven't been released a final ECMAScript 4 version. (The previous release was <a href="http://www.ecma-international.org/publications/standards/Ecma-262.htm">ECMAScript 3</a> from 1999!) The reason is this: The ECMAScript 4 version was a large, monolithic specification where a great number of new features were introduced all at once. Some parts of the working group felt that this was far to ambitious, and wanted lesser, incremental improvements to the language. It was therefore decided to evolve the language in smaller steps over the course of several spec releases.</p><p>Perhaps to avoid confusion, the working group have decided to simply skip the version number 4, and jump straight to ECMAScript 5 - although ECMAScript 5 is a small subset of what as planned for ECMAScript 4. The next version after that, ECMAScript 6 (code named "Harmony") is under active development, and it is still not settled what it will encompass. There may very well be a ECMAScript 7 or 8 beyond that.</p><p>Since Mascara already implements a large part of what was proposed for ECMAScript 4, it is far more advanced than ECMAScript 5, and perhaps even more advanced than ECMAScript 6 will turn out. We will see.</p><p>Here is a overview  of ECMAScript 5 and how it relates to Mascara.</p><p><span style="font-weight: bold;">New features</span><br/>There is a  number of new features, like getters/setter and the higher-order array methods like <span style="font-family:courier new;">map</span>, <span style="font-family:courier new;">reduce</span>, <span style="font-family:courier new;">forEach </span>etc. These features are available in Mascara 1.1 (and will be detailed in a later post).<br/>They are also the foundation for features  like array comprehensions and for-each loops which may be introduced in ES6 (and which already are available in Mascara).</p><p><span style="font-weight: bold;">Attribute-control and object-lockdown</span><br/>There is a number of core methods in ECMAScript 5 which allows the programmer to "seal" and "freeze" objects, and to to manipulate mutability and enumerability of object properties. John Resig have a written a <a href="http://ejohn.org/blog/ecmascript-5-objects-and-properties/">good overview</a> of this. This level of control cannot be implemented or emulated in Mascara, since they require direct support in the language engine. However Mascara solves many of the uses cases for this using <span style="font-weight: bold;">const </span>variables, non-dynamic objects and in general the type system ensures at compile time that you don't modify values that are supposed to be immutable.</p><p>ECMA is definitely doing the right thing by strengthening the foundation of the language with this new level of control. However, it will probably take many years before this is broadly supported, so until then static guarantees (like what Mascara can provide) is a lot better than nothing.</p><p><span style="font-weight: bold;">Strict mode</span><br/>ECMAScript 5 introduces a strict mode, where some of the more reckless styles of programming JavaScript is disallowed. For example the notoriously dangerous <span style="font-family:courier new;">with</span>-statement is disallowed, it is illegal to assign to a variable which have not been declared and so on. This should help catch a bunch of bugs.</p><p>Compared to this Mascara is only halfway strict. Some parts of strict mode, like the requirement that variables  must be declared, is also required in Mascara. On the other hand, <span style="font-family:courier new;">with</span> is still allowed, although the compiler will give you a warning. Generally Mascara takes a passive-aggressive approach to strictness, where the compiler will complain (using warnings) about a lot of potentially unsafe code (e.g. using <span style="font-family:courier new;">with</span>, type errors and so on), but will still allow it. A compilation will only fail if it is totally impossible to the compiler to generate meaningful output. The filp side to this is that users of Mascara should pay attention to warnings, since unsafe code which would be flagged as a compiler error in more strict languages (like Java or C#) only will lead to a warning in Mascara.</p><p>I am contemplating introducing a way to customize the pedantic level of the Mascara compiler. I think it would be useful with a "strict" mode where all type mismatches led to errors, not just warnings. Suggestions from readers are welcome!</p><p>In general ECMAScript 5 is a well thought-out and important spec, but it is also somewhat unexciting for most developers. Many of the features are foundational work, and they only become interesting when you start to build more advanced language features on top of them. However, the future looks bright!</p>]]></content></entry></feed>