<?xml version='1.0' encoding='utf-8' ?>
<feed xmlns="http://www.w3.org/2005/Atom"><id>http://brianmckenna.org/blog/</id><link href="http://brianmckenna.org/blog/" /><link rel="self" type="application/atom+xml" href="http://brianmckenna.org/blog/feed" /><title>BAM Weblog</title><updated>2012-02-19T00:00:00Z</updated><entry><id>http://brianmckenna.org/blog/fpsyd_presentation_roy</id><title>Roy - fp-syd</title><published>2012-02-19T00:00:00Z</published><updated>2012-02-19T00:00:00Z</updated><link href="http://brianmckenna.org/blog/fpsyd_presentation_roy" /><author><name>Brian McKenna</name></author><content type="html"><![CDATA[<p>This week I presented at <a href="http://fp-syd.ouroborus.net/">fp-syd</a>. I've put the <a href="http://brianmckenna.org/files/presentations/fp-syd-roy/">slides</a> online. I talked about why JavaScript needs to be improved for functional programming:</p>

<p><a href="http://brianmckenna.org/files/presentations/fp-syd-roy/">
<img src="http://brianmckenna.org/blog/static/fp-syd-1.png" alt="" title="" />
</a></p>

<p>What options existed before I started Roy:</p>

<p><a href="http://brianmckenna.org/files/presentations/fp-syd-roy/">
<img src="http://brianmckenna.org/blog/static/fp-syd-2.png" alt="" title="" />
</a></p>

<p>Why those options were suboptimal:</p>

<p><a href="http://brianmckenna.org/files/presentations/fp-syd-roy/">
<img src="http://brianmckenna.org/blog/static/fp-syd-3.png" alt="" title="" />
</a></p>

<p>What I'm trying to achieve:</p>

<p><a href="http://brianmckenna.org/files/presentations/fp-syd-roy/">
<img src="http://brianmckenna.org/blog/static/fp-syd-4.png" alt="" title="" />
</a></p>

<p>And what Roy currently is:</p>

<p><a href="http://brianmckenna.org/files/presentations/fp-syd-roy/">
<img src="http://brianmckenna.org/blog/static/fp-syd-5.png" alt="" title="" />
</a></p>

<p>I got a lot of positive feedback which was motivating. I also heard some more news on using type inference in JavaScript engines for performance. It'd be great if we could figure out a way to use Roy's type information within those engines.</p>]]></content></entry><entry><id>http://brianmckenna.org/blog/roy_repl_improvements</id><title>Roy - REPL Improvements</title><published>2012-02-12T00:00:00Z</published><updated>2012-02-12T00:00:00Z</updated><link href="http://brianmckenna.org/blog/roy_repl_improvements" /><author><name>Brian McKenna</name></author><content type="html"><![CDATA[<p>I've added a few improvements to the Roy REPL.</p>

<p>You can now see the type of assigned identifiers with the <code>:t</code> directive:</p>

<pre><code>roy&gt; let x = 100
roy&gt; :t x
Number
roy&gt; let a = [1, 2, 3]
roy&gt; :t a
[Number]
</code></pre>

<p>A structure's values are printed instead of <code>[object Object]</code>:</p>

<pre><code>roy&gt; let x = {a: 1, b: true, c: "three"}
roy&gt; x
{"a":1,"b":true,"c":"three"} : {a: Number, b: Boolean, c: String}
</code></pre>

<p>A helpful message is now shown when the lexer fails:</p>

<pre><code>roy&gt; can't lex this
Couldn't tokenise: 't lex this
</code></pre>

<p>And you can choose not to include the prelude when running files:</p>

<pre><code>$ ./roy -p examples/option.roy 
{ _0: 6 }
</code></pre>

<p>Hopefully this will make the REPL experience a bit nicer.</p>]]></content></entry><entry><id>http://brianmckenna.org/blog/roy_dom</id><title>Roy - DOM Tests</title><published>2012-02-05T00:00:00Z</published><updated>2012-02-05T00:00:00Z</updated><link href="http://brianmckenna.org/blog/roy_dom" /><author><name>Brian McKenna</name></author><content type="html"><![CDATA[<p>This week I did minor work on making <a href="http://brianmckenna.org/blog/roy_browser_modules">browser modules</a> work more smoothly.</p>

<p>In the "modules" branch, the website will have a few "document" definitions in the "dom" module. For example, there's a partial definition for "getElementById":</p>

<p><img src="http://brianmckenna.org/blog/static/roy_dom.png" alt="" title="" /></p>

<p>As you can see, passing a Number doesn't work because it expects a String.</p>

<p>I manually defined parts of the "document" object. The next step would be to use something like IDL to automatically generate the Roy module.</p>]]></content></entry><entry><id>http://brianmckenna.org/blog/roy_browser_modules</id><title>Roy - Browser Modules</title><published>2012-01-29T00:00:00Z</published><updated>2012-01-29T00:00:00Z</updated><link href="http://brianmckenna.org/blog/roy_browser_modules" /><author><name>Brian McKenna</name></author><content type="html"><![CDATA[<p>This week I started work on Roy browser modules. The code is the same as node.js modules. So this:</p>

<pre><code>let obj = {x: 1, y: 2, t: "test"}
export obj
</code></pre>

<p>Will compile into this (in browser mode):</p>

<pre><code>var _obj;
(function() {
var obj = {
"x": 1,
"y": 2,
"t": "test"
};
_obj = obj;
})();
</code></pre>

<p>It currently prefixes the global variables with an underscore. This was just for the initial version and I hope to get rid of it soon.</p>]]></content></entry><entry><id>http://brianmckenna.org/blog/roy_node_modules</id><title>Roy - node.js Modules</title><published>2012-01-22T00:00:00Z</published><updated>2012-01-22T00:00:00Z</updated><link href="http://brianmckenna.org/blog/roy_node_modules" /><author><name>Brian McKenna</name></author><content type="html"><![CDATA[<p>This week I was at <a href="http://linux.conf.au/">linux.conf.au 2012</a> in Ballarat. I talked about <a href="http://altjs.org/">altJS</a> (languages that compile to JavaScript). The video is <a href="http://www.youtube.com/watch?v=Grgz5yBhvRo">up on YouTube</a>.</p>

<p>During my off-time, I worked on Roy's <a href="https://github.com/pufuwozu/roy/tree/modules">modules</a> branch and made it capable of importing and exporting node.js modules. The branch adds an "export" macro:</p>

<pre><code>let obj = {x: 1, y: 2, t: "test"}
export obj
</code></pre>

<p>This will assign the identifier to the "exports" global specified by <a href="http://nodejs.org/docs/latest/api/modules.html">CommonJS Modules/1.0</a>:</p>

<pre><code>var obj = {
    "x": 1,
    "y": 2,
    "t": "test"
};
exports["obj"] = obj;
</code></pre>

<p>My work on <a href="http://brianmckenna.org/blog/roy_separate_compilation">separate compilation</a> causes a ".roym" file to be written during compilation:</p>

<pre><code>obj: {x: Number, y: Number, t: String}
</code></pre>

<p>On the other side, there's an "import" macro:</p>

<pre><code>import "./structural"

let f o = o.x + o.y
f structural.obj
</code></pre>

<p>Which loads the ".roym" file and assigns the types under the module name and compiles to node.js compatible requires:</p>

<pre><code>var structural = require("./structural");
var f = function(o) {
    return o.x + o.y;
}
f(structural.obj)
</code></pre>

<p>That's it. Type-safe node.js modules. Awesome.</p>

<p>I have a few things to continue with:</p>

<ul>
<li>Add flags to change macros to target browser globals and <a href="https://github.com/amdjs/amdjs-api/wiki/AMD">AMD</a> modules</li>
<li>Fix writing <em>all</em> top-level type information to the ".roym" file; only write exported values</li>
</ul>]]></content></entry><entry><id>http://brianmckenna.org/blog/roy_docs_types</id><title>Roy - Type System Documentation</title><published>2012-01-15T00:00:00Z</published><updated>2012-01-15T00:00:00Z</updated><link href="http://brianmckenna.org/blog/roy_docs_types" /><author><name>Brian McKenna</name></author><content type="html"><![CDATA[<p>This week I wrote some simple documentation about Roy's type system.</p>

<p><a href="http://readthedocs.org/docs/roy/en/latest/types.html">
<img src="http://brianmckenna.org/blog/static/roy_types_docs.png" alt="" title="" />
</a></p>

<p>I'm going to write about functions in the next chapter.</p>]]></content></entry><entry><id>http://brianmckenna.org/blog/type_errors_as_warnings</id><title>Type Errors as Warnings</title><published>2012-01-11T00:00:00Z</published><updated>2012-01-11T00:00:00Z</updated><link href="http://brianmckenna.org/blog/type_errors_as_warnings" /><author><name>Brian McKenna</name></author><content type="html"><![CDATA[<p>I follow some programming language people on Twitter. Last week an interesting discussion broke out between David Pollak, James Iry and Paul Snively. Eventually Manuel Simoni, Daniel Spiewak and others got involved.</p>

<p>David Pollak (<a href="http://twitter.com/dpp">@dpp</a>) is working on a <a href="http://blog.visi.io/it-was-20-years-ago-today">new programming language</a>, he imagines it as a cross between Haskell and Excel. He asked:</p>

<blockquote>
  <p>Should code fail to compile if tests/contract and documentation are missing for public functions/structures/methods?</p>
</blockquote>

<p>Paul Snively (<a href="http://twitter.com/psnively">@psnively</a>) mentioned that types are all of the above:</p>

<blockquote>
  <p>@dpp Of course it should fail to compile if your types are wrong. ;-)</p>
</blockquote>

<p>James Iry (<a href="http://twitter.com/jamesiry">@jamesiry</a>) said maybe compile-time type errors could instead become warnings and emit runtime errors:</p>

<blockquote>
  <p>@psnively It's sometimes useful for an IDE to "warn" on type errors and generate exception code in place of the type problem.</p>
</blockquote>

<p>The <a href="http://james-iry.blogspot.com/2012/01/type-errors-as-warnings.html">Eclipse JDT compiler is one that does this</a>. I'm not sure why the Eclipse IDE needed this functionality but it seems like the <a href="http://www.playframework.org/">Play framework</a> uses it to present nice-looking compilation errors on page refresh:</p>

<p><a href="http://www.playframework.org/documentation/1.0.1/guide1">
<img src="http://brianmckenna.org/blog/static/play-guide1-3-small.png" alt="" title="" />
</a></p>

<p>The compiler works by noticing type errors (amongst others) like this:</p>

<pre><code>int foo(String x) {
    return x * 2;
}
</code></pre>

<p>But continues by emitting code like this:</p>

<pre><code>int foo(String x) {
    throw new TypeError("Expected an int but got a String at line 42 of Bar.java.");
}
</code></pre>

<p>Play comes along, catches that runtime exception and turns it into a pretty screen.</p>

<h3>Haskell</h3>

<p>Interestingly, this is exactly what Simon Peyton-Jones talked to me about during a <a href="http://yownightsydneydec11.eventbrite.com/">YOW! Night</a> here in Sydney. His idea is that people want to be able to run programs, even when the compiler is telling them that parts are wrong. He wants to add a mode to the Glasgow Haskell Compiler so code like this:</p>

<pre><code>foo :: String -&gt; Int
foo x = x * 2
</code></pre>

<p>Is transformed into:</p>

<pre><code>foo :: String -&gt; Int
foo x = error "Expected an Int but got a String at line 2 of Foo.hs"
</code></pre>

<p>And the Haskell compiler will print a warning during compilation:</p>

<pre><code>WARNING: Foo.hs:2:8:
    Couldn't match expected type `Int' against inferred type `String'
    In the expression: x * 2
In the definition of `foo': foo x = x * 2
</code></pre>

<p>The following program would execute fine with no command-line arguments but otherwise show the type error at <em>runtime</em>:</p>

<pre><code>import System (getArgs)

main = do
  args &lt;- getArgs
  print $ if length args &gt; 0 then foo [1, 2, 3] else 100
</code></pre>

<p>This might be useful for incomplete refactoring during development. You can modify part of your program and still run that part's tests while the types in other parts have become inconsistent.</p>

<p>Manuel Simoni (<a href="http://twitter.com/msimoni">@msimoni</a>) says it's also beneficial to go into inconsistency while redefining parts of your program, interactively:</p>

<blockquote>
  <p>Without the ability to be inconsistent, you can't support the Lisp Experience™</p>
</blockquote>

<p>In any case, you'd definitely want to turn on treating type warnings as errors in production code.</p>

<h3>Questions</h3>

<p>Do you think this is a good option for statically-typed languages?</p>

<p>Simon seems to think this could attract fans of dynamic languages to Haskell. Would this sole feature satisfy them?</p>

<p>Temporary inconsistencies also <a href="http://www.unlimitednovelty.com/2011/03/distributed-systems-and-dynamic-typing.html">play a part in distributed systems</a>, could a similar idea be used?</p>]]></content></entry><entry><id>http://brianmckenna.org/blog/roy_docs</id><title>Roy - Documentation</title><published>2012-01-08T00:00:00Z</published><updated>2012-01-08T00:00:00Z</updated><link href="http://brianmckenna.org/blog/roy_docs" /><author><name>Brian McKenna</name></author><content type="html"><![CDATA[<p>This week I wrote the first piece of documentation for Roy - an <a href="http://readthedocs.org/docs/roy/en/latest/introduction.html">introduction</a> to a guide through Roy. The project uses <a href="http://sphinx.pocoo.org/">Sphinx</a> and <a href="http://readthedocs.org/">Read the Docs</a> (thanks to <a href="http://www.distractable.net/">Damon Oehlman</a> for pointing me towards that).</p>

<p><a href="http://readthedocs.org/docs/roy/en/latest/introduction.html">
<img src="http://brianmckenna.org/blog/static/roy_introduction.png" alt="" title="" />
</a></p>

<p>The introduction covers why JavaScript isn't enough, the options that we have for not using JavaScript and the path that Roy takes. The next chapter will be on compile-time type-checking, one of the things that makes Roy unique for an altJS language.</p>]]></content></entry><entry><id>http://brianmckenna.org/blog/literate_roy</id><title>Roy - Literate Roy</title><published>2012-01-01T00:00:00Z</published><updated>2012-01-01T00:00:00Z</updated><link href="http://brianmckenna.org/blog/literate_roy" /><author><name>Brian McKenna</name></author><content type="html"><![CDATA[<p>I added some <a href="http://en.wikipedia.org/wiki/Literate_programming">literate programming</a> support to Roy. You can write Markdown files with an extension of <code>.lroy</code> and the <code>roy</code> executable will accept them.</p>

<p>I've also written a shell script that will run it through Pandoc to give you <a href="http://brianmckenna.org/blog/static/sqrt.htm">nice-looking HTML output</a>, using <a href="http://kev.inburke.com/">Kevin Burke's</a> <a href="http://kevinburke.bitbucket.org/markdowncss/">Markdown.css</a>:</p>

<p><a href="http://brianmckenna.org/blog/static/sqrt.htm">
<img src="http://brianmckenna.org/blog/static/literate_roy.png" alt="" title="" />
</a></p>

<p>The above was generated using the following Markdown:</p>

<pre><code>% Roy - Babylonian Square Root

This is a Markdown file. It's also literate Roy code!

We're going to define a `sqrt` function using the
[Babylonian method][] for approximation.

    let sqrt n =

Making a good initial guess helps reduce the amount of
iterations until convergence. One method is to find the
highest-bit (`b`) and use `2^(b/2)`.

      let highestBit n i =
        if (1 &lt;&lt; i) &gt; n then
          i
        else
          highestBit n (i + 1)

      let guess = 1 &lt;&lt; ((highestBit n 1) / 2)

Iteratively average the guess and the number divided by the guess
until convergence with a cut-off of 0.001. The guessing is started
from the initial value, calculated above.

      let nextGuess g =
        if (Math.abs (g - (n / g))) &lt; 0.001 then
          g
        else
          nextGuess ((g + (n / g)) / 2)

      nextGuess guess

Now we can calculate the square root of 314 and print it.

    console.log (sqrt 314)

We should get an answer of around 17.720.

[Babylonian method]: http://en.wikipedia.org/wiki/Methods_of_computing_square_roots#Babylonian_method
</code></pre>

<p>Happy New Year!</p>]]></content></entry><entry><id>http://brianmckenna.org/blog/roy_chrome_rome</id><title>Rome - Roy as Chrome Extension</title><published>2011-12-25T00:00:00Z</published><updated>2011-12-25T00:00:00Z</updated><link href="http://brianmckenna.org/blog/roy_chrome_rome" /><author><name>Brian McKenna</name></author><content type="html"><![CDATA[<p>Rome is a Google Chrome Extension for compiling and editing Roy files. A developer can install <a href="https://github.com/pufuwozu/roy/tree/master/misc/chrome-extension">the unpacked extension</a> (currently only in the <a href="https://github.com/pufuwozu/roy">Roy repository</a>) then just drag a .roy file into the browser.</p>

<p>The file will be compiled and can be executed:</p>

<p><img src="http://brianmckenna.org/blog/static/roy_chrome_rome.png" alt="" title="" /></p>

<p>I decided to steal this while watching a <a href="http://dartlang.org/">Dart</a> presentation at <a href="http://sydjs.com/">SydJS</a>. The presenter mentioned the general idea and I later found out it was called <a href="http://dartwatch.com/index.php/2011/12/frog-toss-tip-and-in-browser-compiling/">Dart Tip</a>. Rome tries to do exactly what Dart Tip does for Dart. Thanks for the idea, Dart team!</p>

<p>Merry Christmas!</p>]]></content></entry><entry><id>http://brianmckenna.org/blog/roy_separate_compilation</id><title>Roy - Separate Compilation</title><published>2011-12-18T00:00:00Z</published><updated>2011-12-18T00:00:00Z</updated><link href="http://brianmckenna.org/blog/roy_separate_compilation" /><author><name>Brian McKenna</name></author><content type="html"><![CDATA[<p>Up until now you've had to compile all Roy modules at once so that
type information would be kept around.</p>

<p>This week I started work on separate compilation Roy. With the latest
changes, a <code>.roym</code> file is generated on compilation that defines all
top level types, like so:</p>

<pre><code>even: Function(Number,Boolean)
odd: Function(Number,Boolean)
succ: Function(Number,Number)
pred: Function(Number,Number)
</code></pre>

<p>Currently the compiler only reads lib/prelude.roym for type
information. I'm going to add a flag to specify where to read modules
from.</p>

<p>This should be a start to a few issues:</p>

<ul>
<li><a href="https://github.com/pufuwozu/roy/issues/17">Add a way to give types to JS globals</a></li>
<li><a href="https://github.com/pufuwozu/roy/issues/18">IDL binding generator</a></li>
</ul>]]></content></entry><entry><id>http://brianmckenna.org/blog/roy_pretty_printing</id><title>Roy - Pretty Printing</title><published>2011-12-11T00:00:00Z</published><updated>2011-12-11T00:00:00Z</updated><link href="http://brianmckenna.org/blog/roy_pretty_printing" /><author><name>Brian McKenna</name></author><content type="html"><![CDATA[<p>This week I created an initial version of a <a href="http://en.wikipedia.org/wiki/Prettyprint">pretty printer</a> for Roy code. The REPL will now take a <code>:s</code> command pointing at a bound name, like so:</p>

<pre><code>roy&gt; let x= \a-&gt;   a+ 100
roy&gt; :s x
\a -&gt; a + 100
</code></pre>

<p>Notice that it pads out the operators. It also works on things like arrays and objects:</p>

<pre><code>roy&gt; let y = [1,2,3]
roy&gt; :s y
[1, 2, 3]
roy&gt; let z = {a: 1   , b:true, c:   "three"}
roy&gt; :s z
{a: 1, b: true, c: "three"}
</code></pre>

<p>I have futures plans to expand this into a standalone formatter so that Roy source will have something like <a href="http://golang.org/cmd/gofmt/">gofmt</a>.</p>

<p>In other Roy news:</p>

<ul>
<li>We have <a href="https://github.com/pufuwozu/roy/blob/master/examples/ajaxmonad.roy">some</a> <a href="https://github.com/pufuwozu/roy/blob/master/examples/deferredmonad.roy">better</a> monad examples</li>
<li>I <a href="https://github.com/pufuwozu/roy/commit/7ff4ac22b2d0a1ebdc80e162f1b1d64ced330c8f">fixed</a> a bug in recursive functions using data constructors</li>
<li>The Roy version that the site is based off has been added to the footer of <a href="http://roy.brianmckenna.org/">http://roy.brianmckenna.org/</a></li>
</ul>]]></content></entry><entry><id>http://brianmckenna.org/blog/roy_recursive_data</id><title>Roy - Recursive Data</title><published>2011-12-04T00:00:00Z</published><updated>2011-12-04T00:00:00Z</updated><link href="http://brianmckenna.org/blog/roy_recursive_data" /><author><name>Brian McKenna</name></author><content type="html"><![CDATA[<p>Last week I blogged that this wasn't possible in Roy:</p>

<pre><code>data List a = Cons a (List a) | Nil
</code></pre>

<p>My one goal for this week was to make that possible. I <a href="https://bitbucket.org/puffnfresh/roy/changeset/f8465a08756f">managed to succeed</a> and you can now even write fancier things like this:</p>

<pre><code>data Tree a = TEmpty | TBranch a (Tree a) (Tree a)

console.log (TBranch 100 TEmpty (TBranch 100 TEmpty TEmpty))

// Won't compile:
// console.log (TBranch 100 TEmpty (TBranch "ASDF" TEmpty TEmpty))
</code></pre>

<p>I also fixed some simple problems with <a href="https://github.com/pufuwozu/roy/issues/24">multiple</a> <a href="https://github.com/pufuwozu/roy/issues/25">declarations</a> of things.</p>

<p>A very cool contribution has been a Roy TextMate/Sublime bundle:</p>

<p><a href="https://github.com/paulmillr/roy.tmbundle">
<img src="http://brianmckenna.org/blog/static/roy-textmate.png" alt="" title="" />
</a></p>

<p>Other awesome contributions have been:</p>

<ul>
<li><a href="https://github.com/pufuwozu/roy/issues/33">Unicode operators</a></li>
<li><a href="https://github.com/pufuwozu/roy/pull/48">REPL improvements</a></li>
<li>New <a href="https://github.com/pufuwozu/roy/issues/34">bind</a> and <a href="https://github.com/pufuwozu/roy/issues/31">lambda syntax</a></li>
<li>New <a href="https://github.com/pufuwozu/roy/issues/14">example</a></li>
</ul>]]></content></entry><entry><id>http://brianmckenna.org/blog/big_roy_news</id><title>Roy's Big Week</title><published>2011-11-27T00:00:00Z</published><updated>2011-11-27T00:00:00Z</updated><link href="http://brianmckenna.org/blog/big_roy_news" /><author><name>Brian McKenna</name></author><content type="html"><![CDATA[<p>Roy was submitted to Hacker News about 2 days ago and received over 100 votes and 47 comments! Crazy.</p>

<p>This is after I created a <a href="https://github.com/pufuwozu/roy">GitHub mirror</a> where <a href="http://paulmillr.com/">Paul Miller</a> filled out the <a href="https://github.com/pufuwozu/roy/issues">issue tracker</a>. I'm trying to work through the biggest bugs and then move onto extra features. Currently the biggest issue is the lack of <a href="https://bitbucket.org/puffnfresh/roy/issue/1/recursive-data-type">recursive data types</a>. That issue is blocking being able to write things like the <a href="http://en.wikipedia.org/wiki/Cons#Lists">cons list</a>:</p>

<pre><code>data List a = Cons a (List a) | Nil
</code></pre>

<p>(Which is also valid Haskell syntax)</p>

<p>This was actually part of a much bigger problem. Data constructors could only have generic parameters and not solid types specified in value constructors. For example, this wouldn't work:</p>

<pre><code>data OptionN = SomeN Number | NoneN
</code></pre>

<p>And that was also a problem with type aliases:</p>

<pre><code>type OptionS = Option String
</code></pre>

<p>Both problems have now been <a href="https://bitbucket.org/puffnfresh/roy/changeset/2b6cf2d4a984">fixed</a>. Now I'm pretty close to fixing the original recursive data type issue.</p>

<p>In other news:</p>

<ul>
<li>Roy now <a href="https://bitbucket.org/puffnfresh/roy">uses Git</a> (clone this new repo if you have an old Mercurial version)</li>
<li>Roy is now in <a href="https://github.com/balupton/docpad">DocPad</a>!</li>
<li>Roy is now in <a href="http://search.npmjs.org/#/roy">npm</a></li>
<li>I fixed <code>do</code> notation not being typed correctly</li>
</ul>

<p>It's been awesome to see such positive feedback. Thanks everyone.</p>]]></content></entry><entry><id>http://brianmckenna.org/blog/sydjs_presentation_altjs</id><title>SydJS Presentation on altJS</title><published>2011-11-20T00:00:00Z</published><updated>2011-11-20T00:00:00Z</updated><link href="http://brianmckenna.org/blog/sydjs_presentation_altjs" /><author><name>Brian McKenna</name></author><content type="html"><![CDATA[<p>On Wednesday I gave a presentation about <a href="http://altjs.org/">altJS</a> to <a href="http://www.sydjs.com/">SydJS</a>. I focused on four languages:</p>

<ol>
<li><a href="http://coffeescript.org/">CoffeeScript</a></li>
<li><a href="https://github.com/clojure/clojurescript">ClojureScript</a></li>
<li><a href="http://dartlang.org/">Dart</a></li>
<li><a href="http://roy.brianmckenna.org/">Roy</a></li>
</ol>

<p>I say "focused" but the only thing I said about Dart was that I don't like it and I don't see anything good about it. The next SydJS is going to have someone from Google talking about Dart. Interesting.</p>

<p>A few questions were asked. One was to clarify <a href="https://wiki.mozilla.org/DevTools/Features/SourceMap">source maps</a>. I don't think I did a good job explaining them. They're a way to map from compiled JavaScript to original source files for debugging. The <a href="https://wiki.mozilla.org/DevTools/Features/SourceMap">MozillaWiki</a> has much more detailed info.</p>

<p>Another question was if there were any domain-specific languages. Kind-of. There are languages that are ports of others, languages that target <a href="http://brianmckenna.org/blog/cps_transform_js">callback hell</a> and languages that target security. I don't know of any with limited business domains.</p>

<p><a href="http://balupton.com/">Ben Lupton</a> later on asked me whether Roy was in <a href="http://npmjs.org/">npm</a> (so he could add it to <a href="http://docpad-kitchensink.herokuapp.com/">DocPad</a>). Answer was "no" but now it's in both <a href="http://search.npmjs.org/#/roy">npm</a> and <a href="https://github.com/balupton/docpad/commit/b34d64e8f76e58bee6ddf0400dad07a573913bf8">DocPad</a>!</p>

<p>I've posted the presentation <a href="http://brianmckenna.org/files/presentations/sydjs-altjs/">slides online</a>. Sadly, they will only work in WebKit browsers (e.g. Chrome, Safari and Epiphany).</p>

<p><a href="http://brianmckenna.org/files/presentations/sydjs-altjs/">
<img src="http://brianmckenna.org/blog/static/altjs-1.png" alt="" title="" />
</a></p>

<p><a href="http://brianmckenna.org/files/presentations/sydjs-altjs/">
<img src="http://brianmckenna.org/blog/static/altjs-2.png" alt="" title="" />
</a></p>

<p><a href="http://brianmckenna.org/files/presentations/sydjs-altjs/">
<img src="http://brianmckenna.org/blog/static/altjs-3.png" alt="" title="" />
</a></p>

<p><a href="http://brianmckenna.org/files/presentations/sydjs-altjs/">
<img src="http://brianmckenna.org/blog/static/altjs-4.png" alt="" title="" />
</a></p>

<p><a href="http://brianmckenna.org/files/presentations/sydjs-altjs/">
<img src="http://brianmckenna.org/blog/static/altjs-5.png" alt="" title="" />
</a></p>]]></content></entry><entry><id>http://brianmckenna.org/blog/bigtext_slideshow</id><title>BigText Slideshow</title><published>2011-11-13T00:00:00Z</published><updated>2011-11-13T00:00:00Z</updated><link href="http://brianmckenna.org/blog/bigtext_slideshow" /><author><name>Brian McKenna</name></author><content type="html"><![CDATA[<p><a href="http://www.sydjs.com/">SydJS</a> is on Wednesday and I'm giving a talk about <a href="http://altjs.org/">altJS</a> languages. I recently read Zach Holman's <a href="http://zachholman.com/posts/slide-design-for-developers/">Slide Design for Developers</a> and my biggest enlightenments were:</p>

<ul>
<li>Make text huge</li>
<li>Words as shapes</li>
</ul>

<p>I wanted to experiment with the layout of my slides and focus completely on those. I tried doing it with Keynote and OpenOffice but they weren't making it very easy to create the style I wanted.</p>

<p>I thought doing it in HTML5 and JavaScript would be much easier. There is an awesome library called <a href="http://www.zachleat.com/web/bigtext-makes-text-big/">BigText</a>, it resizes the CSS font-sizeuntil text fits to the container width - perfect for what I wanted.</p>

<p>I've been working on the SydJS slides for a while but tonight I extracted the skeleton and wrote a quick demo:</p>

<p><a href="http://brianmckenna.org/blog/static/bigtext-slideshow/">
<img src="http://brianmckenna.org/blog/static/bigtext-slideshow-1.png" alt="" title="" />
</a></p>

<p><a href="http://brianmckenna.org/blog/static/bigtext-slideshow/">
<img src="http://brianmckenna.org/blog/static/bigtext-slideshow-2.png" alt="" title="" />
</a></p>

<p><a href="http://brianmckenna.org/blog/static/bigtext-slideshow/">
<img src="http://brianmckenna.org/blog/static/bigtext-slideshow-3.png" alt="" title="" />
</a></p>

<p>I've uploaded the <a href="http://brianmckenna.org/blog/static/bigtext-slideshow/">demo online</a>. If you want to create your own presentation, clone the skeleton from <a href="https://bitbucket.org/puffnfresh/bigtext-slideshow">Bitbucket</a>.</p>]]></content></entry><entry><id>http://brianmckenna.org/blog/sexp_scala</id><title>S-expression Compiler in Scala</title><published>2011-11-06T00:00:00Z</published><updated>2011-11-06T00:00:00Z</updated><link href="http://brianmckenna.org/blog/sexp_scala" /><author><name>Brian McKenna</name></author><content type="html"><![CDATA[<p><a href="http://en.wikipedia.org/wiki/John_McCarthy_" title="computer_scientist">John McCarthy</a> passed away a few weeks ago. For those unfamiliar, he invented Lisp.</p>

<p>After I heard the news, I wondered how hard would it be to create a tiny Lisp in Scala. I imagined that Scala's <a href="http://www.codecommit.com/blog/scala/the-magic-behind-parser-combinators">parser combinators</a> would make it very simple.</p>

<p>And then I remembered a project called <a href="https://github.com/qmx/jitescript">Jitescript</a>. Jitescript is a DSL inspired by Ruby's <a href="https://github.com/headius/bitescript">BiteScript</a>. Both are very simple ways to output JVM bytecode.</p>

<p>So, I set out to write a Lisp to JVM bytecode compiler. I managed to fit it into 63 lines of code. Sure, it's not going to compete with <a href="http://clojure.org/">Clojure</a> any time soon but I think it shows how easy it is to write a JVM language. I think we could make it even nicer by adding some Scala magic to Jitescript.</p>

<p>You put the S-expression as an argument to the <a href="https://github.com/harrah/xsbt/wiki">SBT</a> REPL:</p>

<pre><code>&gt; run (- (- (+ (- (+ 99 11) 10) 11) 10) 10)
</code></pre>

<p>And then run the Lisp.class:</p>

<pre><code>$ java Lisp
91
</code></pre>

<p>(Works out to <a href="http://en.wikipedia.org/wiki/McCarthy_91_function">the number 91</a>)</p>

<p>Here are the 63 lines of Scala:</p>

<pre><code>package scalispa

import util.parsing.combinator.RegexParsers

import java.io.{ File, FileOutputStream, PrintStream }

import me.qmx.jitescript.{ JiteClass, CodeBlock }
import me.qmx.jitescript.util.CodegenUtils.{ p, ci, sig }

import org.objectweb.asm.Opcodes._

sealed trait Node
case class SExp(l: List[Node]) extends Node
case class SInt(i: Int) extends Node
case class SIdent(s: String) extends Node

object Parser extends RegexParsers {
  def int = regex("""[0-9]+""".r) ^^ { (i: String) =&gt; SInt(i.toInt) }
  def ident = regex("""[A-Za-z+-/\*]+""".r) ^^ SIdent
  def sexp = "(" ~&gt; rep(node) &lt;~ ")" ^^ SExp
  def node: Parser[Node] = int | ident | sexp
  def apply(s: String) = parse(sexp, s)
}

object Evaluator {
  def compile(b: CodeBlock, n: Node) {
    n match {
      case SExp(Nil) =&gt; {}
      case SExp(x :: xs) =&gt; {
        xs.foreach(compile(b, _))
        compile(b, x)
      }
      case SInt(x) =&gt; b.pushInt(x)
      case SIdent("+") =&gt; b.iadd()
      case SIdent("-") =&gt; b.isub()
      case SIdent("*") =&gt; b.imul()
      case SIdent("/") =&gt; b.idiv()
    }
  }

  def apply(program: SExp) {
    val b = new CodeBlock
    compile(b, program)
    b.iprintln().voidreturn()

    val name = "Lisp"
    val c = new JiteClass(name)
    c.defineMethod("main", ACC_PUBLIC | ACC_STATIC, sig(classOf[Unit], classOf[Array[String]]), b)

    val stream = new FileOutputStream(new File(name + ".class"))
    stream.write(c.toBytes)
    stream.close()
  }
}

object Main {
  def main(args: Array[String]) {
    Parser(args mkString " ") match {
      case Parser.Success(p, _) =&gt; Evaluator(p)
      case a =&gt; println(a)
    }
  }
}
</code></pre>

<p>The code is up on Bitbucket, under the unimaginative repo name of <a href="https://bitbucket.org/puffnfresh/scalispa">Scalispa</a>. Let me know what you think!</p>]]></content></entry><entry><id>http://brianmckenna.org/blog/launch48</id><title>Launch48 Sydney</title><published>2011-10-30T00:00:00Z</published><updated>2011-10-30T00:00:00Z</updated><link href="http://brianmckenna.org/blog/launch48" /><author><name>Brian McKenna</name></author><content type="html"><![CDATA[<p>I just finished 48 hours of <a href="http://sydney.launch48.com/">Launch48 Sydney</a>.</p>

<p>Friday night at 6pm we heard around 20 pitches, voted and then heard more from the top 8. We voted again and split up into 4 teams:</p>

<ul>
<li>Social pet sitting</li>
<li>Social trips</li>
<li>Social gifts</li>
<li>Social volunteer network</li>
</ul>

<p>Notice a social trend?</p>

<p>I chose to be part of the group working on the volunteer network. The idea was to create something a little bit like <a href="http://stackoverflow.com/">StackOverflow</a> but instead of questions/answers we have charities/volunteers.</p>

<p>Charities add their initiatives. Volunteers browse initiatives, choose to participate and receive points that are shown on their profile. The idea is to help get people hooked into contributing to charities.</p>

<p>Our group of 9 built an initial version, put it up on <a href="http://ninefold.com/">Ninefold</a> and made available at <a href="http://www.happytri.be/">HappyTri.be</a>. The main technology used was <a href="http://www.python.org/">Python</a>, <a href="https://www.djangoproject.com/">Django</a> and <a href="http://pinaxproject.com/">Pinax</a>.</p>

<p>Launch48 was a great way for me to get involved in a startup. I had fun, created something interesting, learned some new skills and uncovered something that I think is a big opportunity. I definitely recommend it.</p>]]></content></entry><entry><id>http://brianmckenna.org/blog/roy_aliases</id><title>Roy - Type Aliases</title><published>2011-10-23T00:00:00Z</published><updated>2011-10-23T00:00:00Z</updated><link href="http://brianmckenna.org/blog/roy_aliases" /><author><name>Brian McKenna</name></author><content type="html"><![CDATA[<p>Roy now has a form of type aliasing. You can give names to types, like so:</p>

<pre><code>type Name = String
type Animal = {name: Name, legs: Number}
let zebra: Animal = {name: "Zebra", legs: 4}
</code></pre>

<p>The benefits are mainly for structural types:</p>

<ol>
<li>You don't have to type out a long structure whenever you want to be explicit</li>
<li>Better error messages</li>
</ol>

<p>For example, this is a poorly typed program without an alias:</p>

<pre><code>let getName x = x.firstName ++ x.lastName
console.log (getName {})
</code></pre>

<p>And this is the error message:</p>

<pre><code>Type error: {} is not {firstName: String, lastName: String}
</code></pre>

<p>You can imagine the error would be kind of scary if the structure was heavily nested or had more than just a couple of elements.</p>

<p>This is a poorly typed program with an alias:</p>

<pre><code>type Person = {firstName: String, lastName: String}
let getName (x: Person) = x.firstName ++ x.lastName
console.log (getName {})
</code></pre>

<p>And this is the nicer error message:</p>

<pre><code>Type error: {} is not Person
</code></pre>

<p>I originally wanted inference to use the scope to check which aliases it could satisfy and use the most appropriate:</p>

<pre><code>type Person = {firstName: String, lastName: String}
// `x` is inferred to be Person from the scope
let getName x = x.firstName ++ x.lastName
</code></pre>

<p>Which is something that <a href="http://mth.github.com/yeti/">Yeti</a> is <a href="https://groups.google.com/d/topic/yeti-lang/evblC5cnz5E/discussion">able to do</a>. Instead, I implemented a very simple version that will just propogate explicit aliases. Using the simple version might conflict with my future plans.</p>

<p>Later on I hope to be able to use the type aliases to output nicer JavaScript:</p>

<pre><code> // Roy: type Person = {firstName: String, lastName: String}
 var Person = function(firstName, lastName) {
     this.firstName = firstName;
     this.lastName = lastName;
 };
</code></pre>

<p>And I might even be able to extend aliases to output information about the hierarchy:</p>

<pre><code>// Hypothetical Roy: type Employee = Person with {wage: Number}
var Employee = function(firstName, lastName, wage) {
    Person.call(this, firstName, lastName);
    this.wage = wage;
};
// Just for documentation:
Employee.prototype = new Person();
</code></pre>

<p>But maybe not. I'll have to try it out.</p>

<p>In adding aliases, I fixed something that I wanted to do for a while; using structural types for normal type annotations:</p>

<pre><code>let getName (x: {name: String}) = x.name
console.log (getName {name: "TEST"})
</code></pre>

<p>Let me know what you think.</p>]]></content></entry><entry><id>http://brianmckenna.org/blog/roy_tuples</id><title>Roy - Tuples</title><published>2011-10-16T00:00:00Z</published><updated>2011-10-16T00:00:00Z</updated><link href="http://brianmckenna.org/blog/roy_tuples" /><author><name>Brian McKenna</name></author><content type="html"><![CDATA[<p>Tuples could be implemented in Roy a couple of different ways. The first way is using the ADT support:</p>

<pre><code>data Tuple a b = Tuple2 a b
</code></pre>

<p>I could add some syntactic sugar on top to completely hide the data type.</p>

<p>The second way would be to use a structure, something like this:</p>

<pre><code>type Tuple2 a b = {0: a, 1: b}
</code></pre>

<p>(The above isn't valid Roy code, I don't have type aliases in yet)</p>

<p>I could also add sugar to hide this method. Pretty similar to what ML does.</p>

<p>Because of JavaScript's property access, I can actually compile tuples to JavaScript arrays very easily. That means this:</p>

<pre><code>let x = (1, true, "three")
</code></pre>

<p>Can compile to this:</p>

<pre><code>var x = [1, true, "three"];
</code></pre>

<p>And still compile down as if it was a structure with numeric keys:</p>

<pre><code>x[0] == 1
x[1] == true
x[2] == "three"
</code></pre>

<p>An interesting part of the structural approach is that higher-arity tuples are subtypes of lesser-arity tuples. For example <code>(1, 2, 3)</code> is a subtype of <code>(4, 5)</code>. I'm not sure if this is good or bad thing but ML seems to get away with it.</p>

<p>I'm currently running with the structural way of implementing tuples. I think that having two different possibilities shows a problem with Roy - it doesn't make sense to have two ways of constructing product types. I should just go the ML way and have ADT options only take up to a single parameter.</p>]]></content></entry><entry><id>http://brianmckenna.org/blog/roy_deep_matching</id><title>Roy - Deep Pattern Matching</title><published>2011-10-09T00:00:00Z</published><updated>2011-10-09T00:00:00Z</updated><link href="http://brianmckenna.org/blog/roy_deep_matching" /><author><name>Brian McKenna</name></author><content type="html"><![CDATA[<p>Roy now has deep pattern matching. That means you can write things like:</p>

<pre><code>let xor e = match e
  case (Left (Left n)) = 0
  case (Left (Right n)) = n
  case (Right (Left n)) = n
  case (Right (Right n)) = 0

console.log (xor (Left (Left 100)))
console.log (xor (Left (Right 100)))
console.log (xor (Right (Left 100)))
console.log (xor (Right (Right 100)))
</code></pre>

<p>Which wil output:</p>

<pre><code>0
100
100
0
</code></pre>

<p>Here's some code I wrote while trying to break it:</p>

<pre><code>let x a = match a
  case (Some (Some (Some s))) = s
  case (Some (Some None)) = 0
  case (Some None) = 0
  case None = 0

// Doesn't compile:
// console.log (x (Some (Some (Some None))))

console.log (x (Some (Some (Some 42))))
console.log (x (Some (Some None)))
console.log (x (Some None))
console.log (x None)


data Tuple a b c = Tuple2 a b | Tuple3 a b c

let addTuple t = match t
  case (Tuple3 a (Tuple3 b c d) e) = b + c + d
  case (Tuple3 a (Tuple2 b c) d) = b + c
  case (Tuple2 a (Tuple3 b c d)) = b + c + d
  case (Tuple2 a (Tuple2 b c) d) = b + c

console.log (addTuple (Tuple3 "addTuple" (Tuple2 1 2) "addTuple"))
console.log (addTuple (Tuple3 "addTuple" (Tuple3 1 2 3) "adsf"))
console.log (addTuple (Tuple2 "addTuple" (Tuple2 1 2)))
console.log (addTuple (Tuple2 "addTuple" (Tuple3 1 2 3)))
</code></pre>

<p>Both functions broke the type checking but now work.</p>

<p>I've been working on just deep matching for the past week. I really need to start proving parts of Roy's type system instead of just writing it in JavaScript and hoping it works (and makes sense).</p>]]></content></entry><entry><id>http://brianmckenna.org/blog/roy_improvements</id><title>Roy Improvements</title><published>2011-10-02T00:00:00Z</published><updated>2011-10-02T00:00:00Z</updated><link href="http://brianmckenna.org/blog/roy_improvements" /><author><name>Brian McKenna</name></author><content type="html"><![CDATA[<p>A few people expressed interest in Roy this week. One person had some feature requests so I started working on it again after a delay of over 2 months.</p>

<h3>The <code>with</code> keyword</h3>

<p>Roy is built on the idea of <a href="roy_structural">structural typing</a>. Up until now Roy didn't have a nice way of extending structures - users had to do this:</p>

<pre><code>let addWorldField o = {hello: o.hello, world: false}

// type is: Function({hello: Boolean},{hello: Boolean, world: Boolean})

console.log (addWorldField {hello: true})
</code></pre>

<p>Pretty ugly. My solution was steal the <code>with</code> keyword from <a href="http://mth.github.com/yeti/">Yeti</a>:</p>

<pre><code>console.log (addWorldField {hello: true} with {world: false})
</code></pre>

<h3>Bug fixes</h3>

<p>Along with implementing the <code>with</code> keyword, I fixed some more bugs.</p>

<p>A huge one that had been annoying me for a long time, was a problem with type-checking tags:</p>

<pre><code>// Fixed bug with unification over tags
console.log (Some 1)
console.log (Some "Test")
</code></pre>

<p>When using the REPL or running .roy files with the '-r' flag, the standard library wasn't imported.</p>

<h3>Future</h3>

<p>Coming up next in Roy:</p>

<ul>
<li>Mutable references</li>
<li>Deep pattern matching</li>
</ul>

<p>Hopefully I'll have even more to show next week!</p>]]></content></entry><entry><id>http://brianmckenna.org/blog/time_lapse</id><title>Time Lapse</title><published>2011-09-25T00:00:00Z</published><updated>2011-09-25T00:00:00Z</updated><link href="http://brianmckenna.org/blog/time_lapse" /><author><name>Brian McKenna</name></author><content type="html"><![CDATA[<p>I took a screenshot every minute while I was working on last week's <a href="pyweek_13">PyWeek entry</a>. I used those screenshots to create a time-lapse video:</p>

<iframe width="640" height="360" src="http://www.youtube.com/embed/VDThwoRWk7o" frameborder="0" allowfullscreen></iframe>

<p>The above video is made up of about 20 hours worth of screenshots, compressed down to 2 minutes.</p>

<p>I cleaned up the scripts I wrote and pushed them to <a href="https://bitbucket.org/puffnfresh/timelapser">Bitbucket</a>. Works on both Linux and Mac OS X.</p>]]></content></entry><entry><id>http://brianmckenna.org/blog/pyweek_13</id><title>PyWeek #13</title><published>2011-09-18T00:00:00Z</published><updated>2011-09-18T00:00:00Z</updated><link href="http://brianmckenna.org/blog/pyweek_13" /><author><name>Brian McKenna</name></author><content type="html"><![CDATA[<p>Today was the last day of PyWeek #13. I entered in a team that included four other graduate developers from <a href="http://www.atlassian.com/">work</a>.</p>

<p>The theme was "Mutate!" - we got together and came up with the concept of a tower defence game that used a genetic algorithm to evolve.</p>

<p>We named the game "Smooth Jazz Tower Defence". Here are the instructions form the README:</p>

<blockquote>
  <p>This is a tower defence game with a twist: creeps mutate! The game uses a
  genetic algorithm to select the best creeps and breed them together. A little
  bit of mutation is thrown in for a bit of spice, just like in evolution.</p>
  
  <p>For both creeps and turrets, colours signify the specialties:</p>
  
  <ul>
  <li>Red: health</li>
  <li>Blue: armour</li>
  <li>Green: speed</li>
  </ul>
  
  <p>A good first strategy is to place one of each turret at the start of the map.</p>
  
  <p>To place a turret, click its icon from the right side of the screen. Hover your
  cursor over a bright red square and click.</p>
  
  <p>Sit back, relax and let the smooth jazz sooth your soul.</p>
</blockquote>

<p>I've uploaded a video of the game <a href="http://www.youtube.com/watch?v=UcnVr_XKv3M">to YouTube</a>:</p>

<p><a href="http://www.youtube.com/watch?v=UcnVr_XKv3M">
<img src="http://i1.ytimg.com/vi/UcnVr_XKv3M/0.jpg" alt="" title="" />
</a></p>

<p>The game runs on Windows, Mac, Linux and anything else that supports Pyglet. Download links are on our <a href="http://pyweek.org/e/gradlassians/">PyWeek page</a>.</p>]]></content></entry><entry><id>http://brianmckenna.org/blog/jrevpro</id><title>JReversePro</title><published>2011-09-11T00:00:00Z</published><updated>2011-09-11T00:00:00Z</updated><link href="http://brianmckenna.org/blog/jrevpro" /><author><name>Brian McKenna</name></author><content type="html"><![CDATA[<p>I've always wanted Emacs to be able to open Java class files. This week I picked up the development of <a href="http://github.com/pufuwozu/jreversepro">JReversePro</a> and wrote a little Emacs interface to it.</p>

<p>I started by looking around for an open-source, command-line Java decompiler. Almost all had no activity since 2004-2008. JReversePro was last touched in January, 2010 so seemed like a good candidate to pick up and continue.</p>

<p>I updated the run scripts, made changes to the spacing, started work on JSR-14 (Adding Generics to the Java Programming Language) and wrote an Emacs script for automatically decompiling .class files.</p>

<p>If you want to try it out, build JReversePro:</p>

<pre><code>git clone https://github.com/pufuwozu/jreversepro.git
cd jreversepro
mvn package
</code></pre>

<p>In Emacs, use <code>M-x load-file</code> to load the jrevpro.el file under the scripts directory. Use <code>M-x set-variable jrevpro-script</code> to change the location to the jrevpro script under the same directory. You should now be able to open a .class file and have it automatically decompiled to Java.</p>]]></content></entry><entry><id>http://brianmckenna.org/blog/cloud9_user_script</id><title>Cloud9 User Script</title><published>2011-09-04T00:00:00Z</published><updated>2011-09-04T00:00:00Z</updated><link href="http://brianmckenna.org/blog/cloud9_user_script" /><author><name>Brian McKenna</name></author><content type="html"><![CDATA[<p>This week I created a user script extension for <a href="http://cloud9ide.com/">Cloud9</a>. The idea is to add something like the Emacs <a href="http://www.emacswiki.org/emacs/InitFile">init file</a>. It could also be thought of something like <a href="https://addons.mozilla.org/en-US/firefox/addon/greasemonkey/">Greasemonkey</a>.</p>

<p>You write some JavaScript and it is executed whenever Cloud9 is loaded. My idea behind this was to be able to extend the editor without changing anything server-side.</p>

<p><a href="https://github.com/pufuwozu/cloud9-userscript/blob/master/README.md">See the README</a> for installation instructions. Once installed, a button will appear on the right dock:</p>

<p><img src="http://brianmckenna.org/blog/static/userscript.png" alt="" title="" /></p>

<p>Clicking it will present a code editor. This is where you type in your user script. When you're ready, press Control+Shift+E to evaluate and save the script.</p>

<p><a href="https://github.com/pufuwozu/cloud9-userscript">Clone the repository</a> and try it out!</p>]]></content></entry><entry><id>http://brianmckenna.org/blog/pyweek_8px_reload</id><title>PyWeek - 8 pixels and Python reloading</title><published>2011-08-28T00:00:00Z</published><updated>2011-08-28T00:00:00Z</updated><link href="http://brianmckenna.org/blog/pyweek_8px_reload" /><author><name>Brian McKenna</name></author><content type="html"><![CDATA[<p>I'm organising a team entry into <a href="http://pyweek.org/13/">next month's PyWeek</a> (#13)
- this week I did a bit of preparation.</p>

<h3>Walk cycle in low resolution pixel art</h3>

<p>Time is always limited during PyWeek. To make a nice looking game, you
have to be able to rapidly create art. I've been working on minimising
the amount of pixels used. I think this has two direct benefits:</p>

<ul>
<li>Low resolution graphics look nice</li>
<li>They are very quick and fairly easy to create</li>
</ul>

<p>Ideally I want less than 8x8 pixel characters but I've found that it's
hard to create a nice looking walk animation with limited pixels. My
first take was to create characters with 1px high legs:</p>

<p><img src="http://brianmckenna.org/blog/static/8bit/Cycle3.gif" alt="" title="" /></p>

<p>It's not very obvious that the character is walking. I thought that
some shading might improve the situation:</p>

<p><img src="http://brianmckenna.org/blog/static/8bit/Cycle4.gif" alt="" title="" /></p>

<p>Only a little. Next thought was that the legs just don't have enough
definition. Adding a knee helped a bit:</p>

<p><img src="http://brianmckenna.org/blog/static/8bit/Cycle2.gif" alt="" title="" /></p>

<p>Adding some shading to the legs helped even more:</p>

<p><img src="http://brianmckenna.org/blog/static/8bit/Cycle7.gif" alt="" title="" /></p>

<p>But I wanted something more fluent. I wasn't sure how to create it with
the platformer side/front on view like above but I had an idea of how
I wanted it to look side on:</p>

<p><img src="http://brianmckenna.org/blog/static/8bit/Cycle1Sheet.png" alt="" title="" /></p>

<p><img src="http://brianmckenna.org/blog/static/8bit/Cycle1.gif" alt="" title="" /></p>

<p>Looks nice! I took the animations of each leg and added it back to the
platformer angle:</p>

<p><img src="http://brianmckenna.org/blog/static/8bit/Cycle5.gif" alt="" title="" /></p>

<p>The legs look like a mess half-way into the animation. I thought it
might be caused by the legs being too close together. I moved them
apart by a pixel:</p>

<p><img src="http://brianmckenna.org/blog/static/8bit/Cycle6.gif" alt="" title="" /></p>

<p>It actually looks pretty good! But then I thought, is it really much
of an improvement to one of the simpler ones?</p>

<p><img src="http://brianmckenna.org/blog/static/8bit/Cycle7.gif" alt="" title="" /> <img src="http://brianmckenna.org/blog/static/8bit/Cycle6.gif" alt="" title="" /></p>

<p>In the end, I'm not sure if it's worth the extra work when you're
under heavy time constraints.</p>

<h3>Reloading Python modules</h3>

<p>This PyWeek I want to try to write the game in a style that will allow
for reloading of parts while it's running. It turns out that Python
has a <code>reload</code> built-in that's makes this really simple!</p>

<p>I made a small proof of concept. I created a file called
"constants.py" that included a single constant:</p>

<pre><code>SPEED = 10
</code></pre>

<p>I then wrote some game code. Pressing the right key will move the
player to the right by SPEED pixels. Pressing 'r' will reload the
constants.py file. Using Pyglet:</p>

<pre><code>#!/usr/bin/env python
import pyglet
import constants

window = pyglet.window.Window()

animation = pyglet.image.load_animation('Cycle7.gif')
sprite = pyglet.sprite.Sprite(animation)

@window.event
def on_draw():
    window.clear()
    sprite.draw()

@window.event
def on_key_press(symbol, modifiers):
    if symbol == pyglet.window.key.RIGHT:
        sprite.x += constants.SPEED
    elif symbol == pyglet.window.key.R:
        reload(constants)

pyglet.app.run()
</code></pre>

<p>So while running, I can modify constants.py:</p>

<pre><code>SPEED = 100
</code></pre>

<p>Then switch back to the game, press 'r' and then press the right
button to move the character by 100 pixels! Hopefully this will let 
us rapidly play with game values without having to exit and restart
the game.</p>]]></content></entry><entry><id>http://brianmckenna.org/blog/plus_equals_even</id><title>Odd Odd Even Agda Proof</title><published>2011-08-21T00:00:00Z</published><updated>2011-08-21T00:00:00Z</updated><link href="http://brianmckenna.org/blog/plus_equals_even" /><author><name>Brian McKenna</name></author><content type="html"><![CDATA[<p>I'm reading a book titled "<a href="http://homepages.cwi.nl/~jve/HR/">The Haskell Road to Logic, Maths and Programming</a>", it teaches Haskell by using logic and logic by using Haskell. I'm using the book to get better at reading and writing proofs. I'm also trying to learn languages like <a href="http://coq.inria.fr/">Coq</a> and <a href="http://wiki.portal.chalmers.se/agda/pmwiki.php">Agda</a> to solve exercises in the book.</p>

<p>One of the first exercises in Chapter 3 (The Use of Logic: Proof) is 3.4:</p>

<ul>
<li>Assume that n and m belong to the set of natural numbers</li>
<li>Show that: if m is odd and n is odd then m + n is even</li>
</ul>

<p>My proof involved:</p>

<ul>
<li>n-1 is even</li>
<li>m-1 is even</li>
<li>2 is even</li>
<li>Thus <code>n-1 + m-1 + 2 = n + m</code> is even</li>
</ul>

<p>I decided to try Agda on this proof. First I needed to define a data type for even and odd numbers. I eventually came up with a mutually recursive definition:</p>

<pre><code>mutual
  data Even : Set where
    zeroE : Even
    succE : Odd -&gt; Even
  data Odd : Set where
    succO : Even -&gt; Odd
</code></pre>

<p>The base case is even zero. Every number after is built like so:</p>

<pre><code>succE (succO (succE (succO zeroE)))
</code></pre>

<p>This example represents 4 and belongs to the even set.</p>

<p>The above problem has this type signature:</p>

<pre><code>_odd+_ : Odd -&gt; Odd -&gt; Even
</code></pre>

<p>That is, an odd plus an odd always equals an even.</p>

<p>The first two cases for this function are easy. If either side is one (succO zeroE), then we just increment the other side, which makes it even:</p>

<pre><code>succO zeroE     odd+ n               = succE n
n               odd+ succO zeroE     = succE n
</code></pre>

<p>The last case is a bit confusing. We take 2 off each side to get to the previous odd number, recurse and then add back on the 4 that we subtracted:</p>

<pre><code>succO (succE n) odd+ succO (succE m) = succE (succO (succE (succO (n odd+ m))))
</code></pre>

<p>I started writing the proof in Agda but didn't end up using any dependent types - a unique feature to languages like Agda. My solution could have easily been made by using another language. For example, here is a direct Haskell translation:</p>

<pre><code>data Even = ZeroE | SuccE Odd
data Odd  = SuccO Even

oddPlus :: Odd -&gt; Odd -&gt; Even
oddPlus (SuccO ZeroE) n = SuccE n
oddPlus n (SuccO ZeroE) = SuccE n
oddPlus (SuccO (SuccE n)) (SuccO (SuccE m)) = SuccE $ SuccO $ SuccE $ SuccO $ oddPlus n m
</code></pre>

<p>Maybe I'm not familiar enough with dependent types to use them in my solution. I imagine that a larger chunk of the problem could have been encoded into the type system. Hopefully I'll figure out some tricks as I work through the book.</p>]]></content></entry><entry><id>http://brianmckenna.org/blog/html5xgdd</id><title>GDD HTML5 Challenge</title><published>2011-08-14T00:00:00Z</published><updated>2011-08-14T00:00:00Z</updated><link href="http://brianmckenna.org/blog/html5xgdd" /><author><name>Brian McKenna</name></author><content type="html"><![CDATA[<p>This week I entered the <a href="https://sites.google.com/site/opencallforgdd/the-challenge-1">Google Developer Day HTML5 challenge</a>. The goal was to use HTML5 to do something interesting with the <a href="http://www.google.com/events/developerday/2011/">Google Developer Day</a> logo (a <a href="http://en.wikipedia.org/wiki/Dymaxion_map">dymaxion map</a>):</p>

<p><img src="http://brianmckenna.org/blog/static/html5xgdd/OpenCallVisual.png" alt="" title="" /></p>

<p>Some restrictions:</p>

<ul>
<li>Only HTML5; no plugins</li>
<li>Related to the location of the Developer Day</li>
<li>Licensed under the <a href="http://creativecommons.org/licenses/by/3.0/">Creative Commons Attribution 3.0 Unported License</a></li>
</ul>

<p>I came up with the idea of using WebGL to transform the logo into the <a href="http://en.wikipedia.org/wiki/Sydney_Opera_House">Sydney Opera House</a>. This is what I made:</p>

<p><a href="http://brianmckenna.org/files/html5xgdd/">
  <img src="http://brianmckenna.org/blog/static/html5xgdd/HTML5xGDD.png" alt="" title="" />
</a></p>

<h3>Implementation</h3>

<p>I first looked at <a href="https://github.com/mrdoob/three.js/">three.js</a> to see what options there were for using 3D data and animating it. I found that morph animation was added to three.js as part of the <a href="http://ro.me/">RO.ME</a> project. Perfect!</p>

<p>I imported the SVG logo into <a href="http://blender.org/">Blender</a>. I had some troubles at first but it imported nicely after deleting the text from the vector. The next problem was that each edge had many unnecessary vertices.</p>

<p><img src="http://brianmckenna.org/blog/static/html5xgdd/vertices.gif" alt="" title="" /></p>

<p>I tried extruding the mesh but the polycount increased to about 5,000 - not very acceptable for morphing. I minimised the original polycount largely by using the <a href="http://wiki.blender.org/index.php/Doc:Manual/Modifiers/Mesh/Decimate">Decimate</a> modifier. Decimate would close up a few of the small holes so I decreased the polycount there by manually merging vertices. I eventually got the extruded polycount down to about 300.</p>

<p><img src="http://brianmckenna.org/blog/static/html5xgdd/decimate.gif" alt="" title="" /></p>

<p>For animation, I added a photo of the Opera House as a background for reference. I used shape keys to transform the triangles to corresponding positions/sizes.</p>

<p><img src="http://brianmckenna.org/blog/static/html5xgdd/animation.gif" alt="" title="" /></p>

<p>To export, I just had to step through the timeline and export each frame separately. This created 10 obj files that I could use with the three.js conversion script:</p>

<pre><code>python convert_obj_three.py -i frame_00.obj -o Visual.js -m "frame*.obj"
</code></pre>

<p>The model could then be used with three.js:</p>

<pre><code>var loader = new THREE.JSONLoader(true);
loader.load({
  model: "Visual.js",
  callback: function(geometry) {
    // Create material and add to scene
  }
});
</code></pre>

<p>I wanted animation to be achieved through "scrubbing" the mouse across the X axis. That was pretty easy to implement using three.js morph targets:</p>

<pre><code>var currentFrame = Math.floor(ratio * framesCount);
var transitionAmount = (ratio * framesCount) % 1;

mesh.morphTargetInfluences[currentFrame] = 1 - transitionAmount;
mesh.morphTargetInfluences[currentFrame + 1] = transitionAmount;
</code></pre>

<p>To finish it off, I added some animated three.js particles, a CSS3 gradient for the background and some simple visual cues. I've put <a href="http://brianmckenna.org/files/html5xgdd/">my entry</a> live and pushed <a href="https://bitbucket.org/puffnfresh/html5xgdd">the code</a> to Bitbucket.</p>]]></content></entry><entry><id>http://brianmckenna.org/blog/ringneck</id><title>Ringneck - PASM to JS</title><published>2011-08-07T00:00:00Z</published><updated>2011-08-07T00:00:00Z</updated><link href="http://brianmckenna.org/blog/ringneck" /><author><name>Brian McKenna</name></author><content type="html"><![CDATA[<p><a href="http://parrot.org/">Parrot</a> is designed to be a general purpose virtual machine for dynamic languages. It started as the virtual machine for Perl 6 but <a href="http://trac.parrot.org/parrot/wiki/Languages">many languages</a> are able to target it. I really love that it's high level enough to have awesome interoperability - for example, you should be able to write a class in Python but subclass it in Ruby.</p>

<p>December of last year I started work on a <a href="http://en.wikipedia.org/wiki/Parrot_assembly_language">Parrot Assembly Language</a> (PASM) to JavaScript compiler called Ringneck. Last week I found it again and now I'm releasing it. The idea was that if many languages compile to PASM, I could get many languages to compile to the web just by compiling PASM to JavaScript.</p>

<p>Ringneck takes PASM like this:</p>

<pre><code>  set     I1, 1
  if      I1, TRUE
  print   "False!\n"

  branch  END
TRUE:
  print   "True!\n"
END:
  end
</code></pre>

<p>And compiles to something like this:</p>

<pre><code>var label;
while(true) {
switch(label) {
default:
    opcodes.core.set.apply(null, [{"type":1,"text":"I1","reg":"I","index":1},{"type":2,"text":"1","value":1}]);
    if(regs["I"][1].value != 0) {label = "TRUE"; break;}
    opcodes.io.print.apply(null, [{"type":4,"text":"\"False!\\n\"","value":"False!\n"}]);
    label = "END"; break;
case "TRUE":
    opcodes.io.print.apply(null, [{"type":4,"text":"\"True!\\n\"","value":"True!\n"}]);
case "END":
    flush(); return;
}
}
</code></pre>

<p>I've put a <a href="http://brianmckenna.org/blog/static/ringneck/">demo</a> up. Feel free to <a href="https://bitbucket.org/puffnfresh/ringneck">clone the Bitbucket repo</a>.</p>

<p><img src="http://brianmckenna.org/blog/static/monkey.jpg" alt="" title="" /></p>]]></content></entry><entry><id>http://brianmckenna.org/blog/climacs</id><title>Climacs</title><published>2011-07-31T00:00:00Z</published><updated>2011-07-31T00:00:00Z</updated><link href="http://brianmckenna.org/blog/climacs" /><author><name>Brian McKenna</name></author><content type="html"><![CDATA[<p>This week I tried creating an application with ClojureScript and Google Closure. One idea I've had for a while is an extensible HTML5 text editor.</p>

<p>I'm an avid Emacs user because Emacs is extremely extensible; I'm able to write some Lisp to make Emacs work exactly as I like. I wanted the same concept to be core to my toy editor, you write some JavaScript and extend the editor at runtime.</p>

<p>I didn't get very far because I was constantly running into problems with DOM Ranges. What I did achieve was syntax highlighting (via parse-js.js in UglifyJS) and JavaScript evaluation:</p>

<p><img src="http://brianmckenna.org/blog/static/climacs/screenshot.png" alt="" title="" /></p>

<p>I've put a <a href="http://brianmckenna.org/blog/static/climacs/">demo up</a> and <a href="https://bitbucket.org/puffnfresh/climacs">the code</a> is on Bitbucket. Only tested in Chrome. Editing is very limited and will only work on a single line. Evaluate your JavaScript with CTRL/CMD+J.</p>]]></content></entry><entry><id>http://brianmckenna.org/blog/cps_transform_js</id><title>Escaping Callback Hell with ClojureScript macros</title><published>2011-07-24T00:00:00Z</published><updated>2011-07-24T00:00:00Z</updated><link href="http://brianmckenna.org/blog/cps_transform_js" /><author><name>Brian McKenna</name></author><content type="html"><![CDATA[<p><a href="http://meta2.tumblr.com/post/787368639/javascript-needs-macros">JavaScript needs macros</a>. I've thought this for a long time. This week <a href="http://en.wikipedia.org/wiki/Rich_Hickey">Rich Hickey</a> announced and released <a href="https://github.com/clojure/clojurescript">ClojureScript</a>, a version of <a href="http://clojure.org/">Clojure</a> that compiles to JavaScript! I'm going to try and use ClojureScript's macro system to overcome one of my JavaScript frustrations.</p>

<p>I like the fact that JavaScript is highly event based but code can easily become <em>callback hell</em>. Take this for example:</p>

<pre><code>app.get('/index', function(req, res, next) {
    User.get(req.params.userId, function(err, user) {
        if(err) next(err);
        db.find({user: user.name}, function(err, cursor) {
            if(err) next(err);
            cursor.toArray(function(err, items) {
                if(err) next(err);
                res.send(items);
            });
        });
    });
});
</code></pre>

<p>Yuck! Let's try to fix this with a simpler example. Here are the goals:</p>

<ul>
<li>Write a sequence of function calls</li>
<li>Have each call be wrapped with an asynchronous timeout callback</li>
</ul>

<p>In the end, I want to be able to write code like this:</p>

<pre><code>(timeout/timeout-macro
   (pn "Hello")
   (pn "World")
   (p "Hello")
   (p " ")
   (p "world")
   (p "!")
   (p "!")
   (pn "!")
   (pn (+ 1 2 3))
   (pn "Done"))
</code></pre>

<p>Lisps are great at solving this problem because they are <a href="http://en.wikipedia.org/wiki/Homoiconicity">homoiconic</a>. They can have powerful macro systems because code can be transformed exactly the same as data. Here is the macro I wrote for this problem:</p>

<pre><code>(defmacro timeout-macro [&amp; body]
  (reduce
   (fn [x y]
     `(timer/callOnce (fn [] ~x ~y) 1000))
   `(fn [])
   (reverse body)))
</code></pre>

<p>With the macro, ClojureScript transforms the function calls above into some awesomely ugly JavaScript:</p>

<pre><code>callOnce.call(null, (function () {
  callOnce.call(null, (function () {
    callOnce.call(null, (function () {
      callOnce.call(null, (function () {
        callOnce.call(null, (function () {
          callOnce.call(null, (function () {
            callOnce.call(null, (function () {
              callOnce.call(null, (function () {
                callOnce.call(null, (function () {
                  callOnce.call(null, (function () {
                    return pn.call(null, "Done");
                  }), 1000);
                  return pn.call(null, cljs.core._PLUS_.call(null, 1, 2, 3));
                }), 1000);
                return pn.call(null, "!");
              }), 1000);
              return p.call(null, "!");
            }), 1000);
            return p.call(null, "!");
          }), 1000);
          return p.call(null, "world");
        }), 1000);
        return p.call(null, " ");
      }), 1000);
      return p.call(null, "Hello");
    }), 1000);
    return pn.call(null, "World");
  }), 1000);
  return pn.call(null, "Hello");
}), 1000);
</code></pre>

<p>This is known as an automatic <a href="http://en.wikipedia.org/wiki/Continuation-passing_style">continuation-passing style</a> (CPS) transform. I've put the <a href="http://brianmckenna.org/blog/static/clojurescript-timeout-cps/">demo up here</a> and posted the <a href="https://bitbucket.org/puffnfresh/clojurescript-timeout-cps">code up on Bitbucket</a>.</p>]]></content></entry><entry><id>http://brianmckenna.org/blog/roy_tests</id><title>Roy - Tests (finally)</title><published>2011-07-17T00:00:00Z</published><updated>2011-07-17T00:00:00Z</updated><link href="http://brianmckenna.org/blog/roy_tests" /><author><name>Brian McKenna</name></author><content type="html"><![CDATA[<p>Anybody following along could probably tell that I'm not practising <a href="http://en.wikipedia.org/wiki/Test-driven_development">TDD</a> with Roy. Only this week I started writing some tests. As expected, I'm finding lots of bugs!</p>

<p>I'm going to work on cleaning it up but the test runner currently stands at 24 lines of Roy code:</p>

<pre><code>let fs = require 'fs'
let path = require 'path'
let child_process = require 'child_process'

let dir = "test"
let files = fs.readdirSync dir

let tests = files.filter (fn x =
  (x.lastIndexOf '.roy') == (x.length - 4)
)

tests.forEach (fn t =
  let name = path.join dir t
  let outFile = (path.join dir (path.basename t '.roy')) ++ '.out'
  child_process.exec './roy -r ' ++ name (fn error stdout stderr =
    if error then
      console.log "Error:" error.message
    else
      let expected = fs.readFileSync outFile 'utf8'
      let actual = stdout.toString ()
      console.assert actual == expected "Output of " ++ t ++ ": " ++ (JSON.stringify actual) ++ " does not match " ++ (JSON.stringify expected)
      console.log "Pass:" name
  )
)
</code></pre>

<p>Not too ugly. It seems like some standard library functions could make it nicer.</p>]]></content></entry><entry><id>http://brianmckenna.org/blog/learn_nintendo_ds_a_haskell</id><title>Learn Nintendo DS a Haskell</title><published>2011-07-10T00:00:00Z</published><updated>2011-07-10T00:00:00Z</updated><link href="http://brianmckenna.org/blog/learn_nintendo_ds_a_haskell" /><author><name>Brian McKenna</name></author><content type="html"><![CDATA[<p>This weekend was <a href="http://www.haskell.org/haskellwiki/AusHac2011">AusHac 2011</a>. I spent my time getting Haskell to compile to the Nintendo DS.</p>

<p>I remember reading a while ago about someone using <a href="http://repetae.net/computer/jhc/">JHC</a> to compile a Haskell executable for the iPhone. JHC is a Haskell compiler that outputs fairly sane C code. I figured that it'd be fairly easy to get it to output code to work with <a href="http://devkitpro.org/">devkitPro</a>.</p>

<p>I had <a href="http://twitter.com/puffnfresh/status/17348921600778240">a quick version</a> of this project working in December but I lost the patches and wanted to make a better version.</p>

<p>After a days work I had something compiling and I spent another day playing around with it. I think I created the world's most annoying Haskell program:</p>

<p><img src="http://brianmckenna.org/blog/static/haskell-nds/screenshot.gif" alt="" title="" /></p>

<p>It is much more annoying running on a physical DS:</p>

<p><img src="http://brianmckenna.org/blog/static/haskell-nds/20110710_210754.jpg" alt="" title="" /></p>

<p>I've uploaded <a href="http://brianmckenna.org/blog/static/haskell-nds/haskell-nds.nds">the binary</a> for people to try out. I've put <a href="https://bitbucket.org/puffnfresh/haskell-nds">the example project</a> up on Bitbucket. The main Haskell for the example is:</p>

<pre><code>printFreq freq = do
  consoleClear
  print freq

setSound sound freq = do
  soundSetFreq sound freq
  printFreq freq

keyLoop sound = do
  x &lt;- keyboardUpdate
  scanKeys
  if x &gt; 0 then do
    setSound sound $ x * 100
    putChar $ chr x
  else if isTouching then do
    if getTouchY &lt; 110 then do
      setSound sound $ getTouchY * 100
      print getTouchY
    else
      return ()
    r &lt;- randomRIO (0, 31)
    oamMainColor r 0 0
    oamMainSet getTouchX getTouchY
  else
    return ()

  swiWaitForVBlank
  oamMainUpdate
  keyLoop sound

main = do
  consoleDemoInit
  keyboardDemoInit
  keyboardShow
  soundEnable
  sound &lt;- soundPlayPSG dutyCycle_50 10000 127 64
  oamMainInit
  keyLoop sound
</code></pre>

<p>To compile you have to <a href="http://devkitpro.org/wiki/Getting_Started/devkitARM">setup devkitARM</a> with my <a href="http://sourceforge.net/tracker/download.php?group_id=114505&amp;atid=668551&amp;file_id=417645&amp;aid=3361239">patch to libnds</a>. You then need to <a href="http://repetae.net/computer/jhc/development.shtml">setup JHC</a> with my <a href="http://www.haskell.org/pipermail/jhc/attachments/20110710/11fc461d/attachment.obj">DARCS patch</a>. I've forwarded the patches on so hopefully it will just work in the future!</p>

<p>Before this project, it was possible to run <a href="http://blog.closuretohome.com/2007/12/hugs-for-nintendo-ds.html">Hugs</a> on the DS. While I think that is really awesome, I took the JHC approach for a few reasons:</p>

<ol>
<li>I couldn't figure out an easy way to access C libraries from Hugs.</li>
<li>I wasn't sure how to make Hugs jump straight to executing custom Haskell code.</li>
<li>Hugs is interpreted. I had a feeling that compiling to C and using GCC would give better performance.</li>
</ol>

<p>Although the above example code is fairly ugly, I'm very confident that a nice DSL could be created for writing games. I'd love to see this happen.</p>]]></content></entry><entry><id>http://brianmckenna.org/blog/roy_repl_macros</id><title>Roy - Meta-programming and a REPL</title><published>2011-07-03T00:00:00Z</published><updated>2011-07-03T00:00:00Z</updated><link href="http://brianmckenna.org/blog/roy_repl_macros" /><author><name>Brian McKenna</name></author><content type="html"><![CDATA[<p>Roy now has a limited, <a href="http://en.wikipedia.org/wiki/Metaprogramming">compile-time meta-programming</a> system. Simple example:</p>

<pre><code>macro printArgLength =
  console.log "Compiling to:" arguments.length
  [| console.log &amp;(arguments.length) |]

printArgLength 1
printArgLength 1 2
printArgLength 1 2 3
</code></pre>

<p>The code above will output messages during compilation. This is the JavaScript output:</p>

<pre><code>console.log(1)
console.log(2)
console.log(3)
</code></pre>

<p>I'd really like to make Roy's meta-programming work more like <a href="http://www.haskell.org/ghc/docs/7.0.2/html/users_guide/template-haskell.html">Template Haskell</a> or <a href="http://convergepl.org/documentation/1.2/ctmp/">Converge</a>. Unfortunately I have only skimmed papers on both and used neither. My goal is to make the meta-programming powerful enough to express <a href="http://meta2.tumblr.com/post/787368639/javascript-needs-macros">modules</a> and <a href="roy_monad_syntax">do notation</a>.</p>

<p>I also built a <a href="http://en.wikipedia.org/wiki/Read-eval-print_loop">REPL</a> for Roy in about 20 minutes. Amazing how simple it is to create a nice REPL in <a href="http://nodejs.org/">node.js</a> by using the readline module.</p>

<pre><code>$ ./roy
roy&gt; 10 * 2 - 5
15 : Number
roy&gt; 
</code></pre>]]></content></entry><entry><id>http://brianmckenna.org/blog/roy_standard_library</id><title>Roy - Standard Library</title><published>2011-06-26T00:00:00Z</published><updated>2011-06-26T00:00:00Z</updated><link href="http://brianmckenna.org/blog/roy_standard_library" /><author><name>Brian McKenna</name></author><content type="html"><![CDATA[<p>I spent a large chunk of this week trying to create modules in <a href="http://roy.brianmckenna.org/">Roy</a>. I've thought of countless ways to try and implement them but none of the solutions have been very good. I have two fundamental problems:</p>

<ol>
<li>JavaScript itself doesn't support modules</li>
<li>Roy needs static type information to be useful</li>
</ol>

<p>To illustrate the problem, in CommonJS we do this:</p>

<pre><code>var x = require('./x');
exports.a = x.y;
exports.b = 1;
</code></pre>

<p>In the browser we do this:</p>

<pre><code>window.m = {a: window.x.y, b: 1};
</code></pre>

<p>How do we create a solution that imports/exports type information across both?</p>

<p>I don't think it's possible. I might have to resort to making the Roy compiler modal (CommonJS or bowser modes).</p>

<p>That problem aside. I did commit something this week - the start of a standard library:</p>

<pre><code>console.log (id 1) // 1
console.log (odd 2) // false

console.log (maybe 0 id None) // 0

console.log (head (tail (replicate 10 'a'))) // a
</code></pre>

<p>While writing the standard library I've found a lot of holes in the type system. I'll try to fix them for next week!</p>]]></content></entry><entry><id>http://brianmckenna.org/blog/roy_monad_syntax</id><title>Roy - Monad Syntax</title><published>2011-06-19T00:00:00Z</published><updated>2011-06-19T00:00:00Z</updated><link href="http://brianmckenna.org/blog/roy_monad_syntax" /><author><name>Brian McKenna</name></author><content type="html"><![CDATA[<p>I added monad syntax to <a href="http://roy.brianmckenna.org/">Roy</a>. It is very close to <a href="http://en.wikipedia.org/wiki/Monad_(functional_programming)#do-notation">do-notation</a>, with the exception that the monad implementation is explicit:</p>

<pre><code>data Option a =
  Some a | None

let optionMonad = {
  return: fn x =
    Some x
  bind: fn x f = match x
    case (Some a) = f a
    case None = None
}

console.log (do optionMonad
  bind x = Some 1
  let y = 2
  bind z = Some 3
  return x + y + z
)
</code></pre>

<p>Note the <code>do optionMonad</code>. Explicitness is only necessary because Roy doesn't have any form of interfaces or type classes. An upside is that a single datatype could have multiple monad implementations, something not allowed in most other languages.</p>

<p>I also worked on prettying up the JS output. It now looks like this:</p>

<pre><code>"use strict";
var Some = function(a){this._0 = a};
var None = function(){};
var optionMonad = {
    "return": function(x) {
        return new Some(x);
    },
    "bind": function(x, f) {
        return (function() {
            if(x instanceof Some) {
                var a = x._0;
                return f(a)
            } else if(x instanceof None) {
                return new None()
            }
        })();
    }
};
console.log((function(){
    var __monad__ = optionMonad;
    return __monad__["bind"](new Some(1), function(x) {
        var y = 2;
        return __monad__["bind"](new Some(3), function(z) {
            return __monad__["return"](x + y + z);
        });
    });
})())
</code></pre>]]></content></entry><entry><id>http://brianmckenna.org/blog/roy_structural</id><title>Roy - Structural Typing</title><published>2011-06-12T00:00:00Z</published><updated>2011-06-12T00:00:00Z</updated><link href="http://brianmckenna.org/blog/roy_structural" /><author><name>Brian McKenna</name></author><content type="html"><![CDATA[<p>This week I implemented very simple <a href="http://en.wikipedia.org/wiki/Structural_type_system">structural typing</a> in Roy and <a href="http://roy.brianmckenna.org/">created a website for the project</a>.</p>

<p>Structural typing is a really awesome type system feature. Here's an example:</p>

<pre><code>let obj = {x: 1, y: 2, t: "test"}

let getX a = a.x + 2

console.log (getX obj)
console.log (obj.x + obj.y)

let plusXY a = a.x + a.y
console.log (plusXY obj)
console.log (plusXY {x: 2, y: 1})

let makeXY x y = {x: x, y: y}
console.log (plusXY (makeXY 1 2))
console.log (makeXY 1 2)

// Won't compile
// plusXY {x: 1, z: 2}

console.log ((fn obj = obj.a.a + obj.a.b) {a: {a: 1, b: 2}})

let makeFun a = {f: fn b = a.x + b.y}
console.log ((makeFun {x: 1}).f {y: 2})
</code></pre>

<p>The idea is that an object is a subtype if it can satisfy all of another object's properties.</p>

<p><a href="http://roy.brianmckenna.org/">Visit Roy's website</a> to give the language a try from your browser. I've only tested it in Chrome and Safari. It definitely won't work in IE.</p>]]></content></entry><entry><id>http://brianmckenna.org/blog/roy_pattern_matching</id><title>Roy - Simple Pattern Matching</title><published>2011-06-05T00:00:00Z</published><updated>2011-06-05T00:00:00Z</updated><link href="http://brianmckenna.org/blog/roy_pattern_matching" /><author><name>Brian McKenna</name></author><content type="html"><![CDATA[<p><a href="http://projectaweek.heroku.com/">This week</a> I worked on adding simple <a href="http://en.wikipedia.org/wiki/Tagged_union">tagged unions</a> (sum types) and <a href="http://en.wikipedia.org/wiki/Pattern_matching">pattern matching</a> to <a href="roy">Roy</a>. The <a href="https://bitbucket.org/puffnfresh/roy/changeset/205a1d95d1fe">diff is fairly disgusting</a> but I'm happy that it works. Here is the example I committed:</p>

<pre><code>data Maybe a =
  Some a | None

let printSomething m = match m
  case (Some x) = console.log x
  case None = console.log "Empty"

printSomething (Some 1)
printSomething None

data Either a b =
  Left a | Right b

let printString (s : String) =
  console.log s

let printResult e = match e
  case (Left x) = console.log x
  case (Right x) = printString x

printResult (Left 10)
printResult (Right "Error")

// Won't compile:
// printResult (Right 10)

data Bool =
  True | False

let getBool b ifTrue ifFalse = match b
  case True = ifTrue
  case False = ifFalse

console.log (getBool True 1 2)
console.log (getBool False 1 2)
</code></pre>

<p>Running the above example (with <code>./roy examples/data.roy &amp;&amp; node examples/data.js</code>) will print the following:</p>

<pre><code>1
Empty
10
Error
1
2
</code></pre>

<p>The current version of pattern matching has no exhaustiveness check. I'll try to figure out how to do that later on.</p>]]></content></entry><entry><id>http://brianmckenna.org/blog/roy</id><title>Roy</title><published>2011-05-29T00:00:00Z</published><updated>2011-05-29T00:00:00Z</updated><link href="http://brianmckenna.org/blog/roy" /><author><name>Brian McKenna</name></author><content type="html"><![CDATA[<p>This week I'm releasing a toy functional language that compiles to JavaScript. I've named it "Roy" and you can <a href="https://bitbucket.org/puffnfresh/roy">find it on Bitbucket</a>. It's just over 1000 lines of JavaScript.</p>

<p>It uses my past two projects from <a href="http://projectaweek.heroku.com/">projectaweek</a>:</p>

<ul>
<li><a href="js_type_inference">Type inference</a></li>
<li><a href="js_lexer">Whitespace lexer</a></li>
</ul>

<p>Here's an example of the language:</p>

<pre><code>let gcd a b =
  if b == 0 then
    a
  else
    gcd b (a % b)

console.log (gcd 49 35)
</code></pre>

<p>And here's the (ugly) JavaScript output:</p>

<pre><code>"use strict";
var gcd = function(a, b) {return (function(){if(b == 0){return a}else{return gcd(b, a % b)}})();;};
console.log(gcd(49, 35))
</code></pre>

<p>Roy will serve as the basis for a new language I'm working on. The next language will:</p>

<ul>
<li>Improve JavaScript interop</li>
<li>Structural typing</li>
<li>Tail recursion</li>
<li>Algebraic data types</li>
<li>Pattern matching</li>
<li>Prettify the JavaScript output</li>
</ul>]]></content></entry><entry><id>http://brianmckenna.org/blog/js_lexer</id><title>Simple Lexer in JavaScript</title><published>2011-05-22T00:00:00Z</published><updated>2011-05-22T00:00:00Z</updated><link href="http://brianmckenna.org/blog/js_lexer" /><author><name>Brian McKenna</name></author><content type="html"><![CDATA[<p>I haven't had much time but I'm trying to continue with <a href="http://www.shimweasel.com/2011/05/08/the-stewart-method-how-not-to-suck">releasing a project every week</a>. This week I've worked on a whitespace-significant lexer for use with <a href="http://jison.org/">Jison</a>.</p>

<p>The <a href="https://bitbucket.org/puffnfresh/js-whitespace-lexer">code</a> is up on Bitbucket. It analyses a small, ML-like language.</p>]]></content></entry><entry><id>http://brianmckenna.org/blog/js_type_inference</id><title>Type Inference in JavaScript</title><published>2011-05-15T00:00:00Z</published><updated>2011-05-15T00:00:00Z</updated><link href="http://brianmckenna.org/blog/js_type_inference" /><author><name>Brian McKenna</name></author><content type="html"><![CDATA[<p>Last week I read about <a href="http://donsbot.wordpress.com/">Don Stewart</a>'s method for productivity: <a href="http://www.shimweasel.com/2011/05/08/the-stewart-method-how-not-to-suck">releasing a project every week</a>. I've been working on a language that <a href="http://altjs.org/">compiles to JavaScript</a> and thought that I could release it in modular parts.</p>

<p>This week I am releasing my JavaScript implementation of <a href="http://en.wikipedia.org/wiki/Type_inference#Hindley.E2.80.93Milner_type_inference_algorithm">Hindley-Milner type inference</a> (a.k.a. Algorithm W).</p>

<p>The <a href="https://bitbucket.org/puffnfresh/js-type-inference/src">source is on Bitbucket</a> and I've generated some literate-style code docs using <a href="http://jashkenas.github.com/docco/">Docco</a>. Check them out here:</p>

<ul>
<li><a href="http://brianmckenna.org/files/js-type-inference/docs/typeinference.html">typeinference.js</a></li>
<li><a href="http://brianmckenna.org/files/js-type-inference/docs/types.html">types.js</a></li>
</ul>]]></content></entry><entry><id>http://brianmckenna.org/blog/minimalist_android_scala_env</id><title>Minimalist Android Scala Environment</title><published>2010-12-28T00:00:00Z</published><updated>2010-12-28T00:00:00Z</updated><link href="http://brianmckenna.org/blog/minimalist_android_scala_env" /><author><name>Brian McKenna</name></author><content type="html"><![CDATA[<p>I managed to get Scala working on Android after the SDK was first released. I also found <a href="https://review.source.android.com/10724">a little problem with the Dalvik virtual machine</a> in the process.</p>

<p>A year and a half went by and I've come back to try Scala on Android. There's now a few resources on the topic, <a href="http://www.assembla.com/wiki/show/scala-ide/Developing_for_Android">even one from ScalaIDE</a>. I haven't been completely satisfied with the solutions I've read so I came up with the following.</p>

<h3>Instructions</h3>

<p>Install <a href="http://www.scala-ide.org/">ScalaIDE</a> in Eclipse and create a new Android project.</p>

<p>Make sure there is a directory called libs and copy in scala-library.jar. Make a new directory called tools and copy in scala-compiler.jar.</p>

<p>Generate an Ant build.xml file:</p>

<pre><code>$ ~/android-sdk-linux_86/tools/android update project --target 1 --path .
</code></pre>

<p>Define a pre-compile stage in build.xml and add a Scala task:</p>

<pre><code>&lt;target name="-pre-compile" depends="-resource-src"&gt;
    &lt;taskdef resource="scala/tools/ant/antlib.xml"
             classpath="tools/scala-compiler.jar:libs/scala-library.jar" /&gt;

    &lt;scalac force="changed" deprecation="on" destdir="${out.classes.absolute.dir}"
            bootclasspathref="android.target.classpath"&gt;
        &lt;src path="${source.absolute.dir}" /&gt;
        &lt;src path="${gen.absolute.dir}" /&gt;
        &lt;src refid="project.libraries.src" /&gt;
        &lt;classpath&gt;
            &lt;fileset dir="${jar.libs.absolute.dir}" includes="*.jar" /&gt;
        &lt;/classpath&gt;
    &lt;/scalac&gt;
&lt;/target&gt;
</code></pre>

<p>Android doesn't work very well when converting a huge amount of Java bytecode to Dalvik bytecode. To get around this, we can use Proguard to remove all unused parts of the Scala library. Enable Proguard for debug releases by adding the following to build.xml:</p>

<pre><code>&lt;target name="-debug-obfuscation-check"&gt;
    &lt;property name="proguard.enabled" value="true" /&gt;
    &lt;path id="out.dex.jar.input.ref" /&gt;
&lt;/target&gt;
</code></pre>

<p>Make the <code>install</code> target local to our build.xml instead of importing it. This will make it easier for Eclipse later on:</p>

<pre><code>&lt;target name="install" depends="debug"&gt;
    &lt;install-helper /&gt;
&lt;/target&gt;
</code></pre>

<p>Add the following line to default.properties:</p>

<pre><code>proguard.config=proguard.cfg
</code></pre>

<p>The Scala library will cause warnings and make Proguard stop. Make it continue by adding the following to proguard.cfg:</p>

<pre><code>-dontwarn
</code></pre>

<p>Remove the default run configuration from Eclipse and add a new external run configuration. The buildfile should be <code>${project_loc}/build.xml</code> and the base directory should be <code>${project_loc}</code>. Go to the "Targets" tab and tick the "install" target.</p>

<p>Delete the default Java source file and recreate it using Scala:</p>

<pre><code>package org.brianmckenna.helloandroid

import android.app.Activity
import android.os.Bundle

class HelloAndroid extends Activity {
  override def onCreate(savedInstanceState: Bundle): Unit = {
    super.onCreate(savedInstanceState)
    setContentView(List(R.layout.main) head)
  }
}
</code></pre>

<p>After starting the emulator and running Ant, Scala should now run on Android!</p>]]></content></entry><entry><id>http://brianmckenna.org/blog/haskell_parallel_perspective</id><title>Haskell: From a Parallel Perspective</title><published>2010-10-13T00:00:00Z</published><updated>2010-10-13T00:00:00Z</updated><link href="http://brianmckenna.org/blog/haskell_parallel_perspective" /><author><name>Brian McKenna</name></author><content type="html"><![CDATA[<p>For class today, I presented some popular parallel libraries for Haskell (using GHC). It covered topics suchs as:</p>

<ul>
<li><code>par</code> and <code>pseq</code></li>
<li><code>parList</code>, <code>parListChunk</code>, <code>parMap</code>, <code>r0</code>, <code>rwhnf</code> and <code>rnf</code></li>
<li>Data Parallel Haskell</li>
<li>Intel CnC</li>
<li><code>forkIO</code> with <code>MVar</code>, <code>Chan</code>, <code>QSemN</code> and <code>STM</code></li>
</ul>

<p>The presentation is online here:</p>

<p><a href="http://brianmckenna.org/files/presentations/haskell-parallel/">http://brianmckenna.org/files/presentations/haskell-parallel/</a></p>

<p>On Bitbucket here:</p>

<p><a href="https://bitbucket.org/puffnfresh/presentations">https://bitbucket.org/puffnfresh/presentations</a></p>

<p>Downloadable as a zip here:</p>

<p><a href="http://brianmckenna.org/files/presentations/haskell-parallel.zip">http://brianmckenna.org/files/presentations/haskell-parallel.zip</a></p>

<p><img src="http://brianmckenna.org/blog/static/lyah_random.png" alt="Random" title="" /></p>

<p><em>Illustration from <a href="http://learnyouahaskell.com/">LYAH</a> by <a href="https://twitter.com/bonus500">bonus500</a></em></p>]]></content></entry><entry><id>http://brianmckenna.org/blog/3yr_old_brian</id><title>When I was 3...</title><published>2010-09-06T00:00:00Z</published><updated>2010-09-06T00:00:00Z</updated><link href="http://brianmckenna.org/blog/3yr_old_brian" /><author><name>Brian McKenna</name></author><content type="html"><![CDATA[<p><img src="http://brianmckenna.org/blog/static/computer_photo_small.jpg" alt="" title="" /></p>]]></content></entry><entry><id>http://brianmckenna.org/blog/wanted_unparallel_project</id><title>Wanted: Unparallel project in need of good optimisation</title><published>2010-07-29T00:00:00Z</published><updated>2010-07-29T00:00:00Z</updated><link href="http://brianmckenna.org/blog/wanted_unparallel_project" /><author><name>Brian McKenna</name></author><content type="html"><![CDATA[<p>I've just started a Parallel Programming class at <a href="http://qut.edu.au/">QUT</a>. Our major assessment (worth 50%) is to manually parallelise some software.</p>

<p>I'm looking for something that:</p>

<ul>
<li>Is interesting</li>
<li>Takes skill and effort</li>
<li>Has some potential barriers</li>
<li>Would be appreciated</li>
<li>Is preferably open-source</li>
</ul>

<p>Do you use any software could use a speed up? Do you have a project that could use some parallelisation?</p>]]></content></entry><entry><id>http://brianmckenna.org/blog/nodejs_webgl</id><title>node.js WebGL</title><published>2010-06-09T00:00:00Z</published><updated>2010-06-09T00:00:00Z</updated><link href="http://brianmckenna.org/blog/nodejs_webgl" /><author><name>Brian McKenna</name></author><content type="html"><![CDATA[<p>I'm about to present something I've been working on recently. Something I'm really happy about!</p>

<h2>A WebGL implementation for <a href="http://nodejs.org/">node.js</a>!</h2>

<p>Here's a screenshot of it next to WebGL in Chromium (even running the same JavaScript):</p>

<p><img src="http://brianmckenna.org/blog/static/nodejs_webgl.png" alt="" title="" /></p>

<p>I've <a href="http://github.com/pufuwozu/node-webgl">chucked it up on GitHub</a> but if you're having a go, be aware that I've only implemented enough OpenGL calls to run my example. I'd really appreciate any help implementing the other functions.</p>

<p>This project is part of something much bigger. Imagine easily writing games or multimedia applications that run in the browser and on the desktop without changes. Stay tuned.</p>]]></content></entry><entry><id>http://brianmckenna.org/blog/gsoc_introduction</id><title>GSoC Introduction</title><published>2010-05-19T00:00:00Z</published><updated>2010-05-19T00:00:00Z</updated><link href="http://brianmckenna.org/blog/gsoc_introduction" /><author><name>Brian McKenna</name></author><content type="html"><![CDATA[<p><em>This post has been taken from <a href="http://gsoc2010.wordpress.com/2010/05/17/introduction/">the WordPress GSoC 2010 blog</a>.</em></p>

<p>I work part-time as a web developer at a marketing and advertising agency which heavily uses WordPress as a CMS. Like many developers, we use local development machines to add new functionality and fix bugs,  we then migrate those websites onto our client’s web servers. If you’re very familiar with WordPress you’ll probably know that migrating an install is fairly horrible. That’s what I plan to fix.</p>

<p>I’ll try to put an easy to use interface (hopefully with some help from the WordPress UI/UX team) that will let the user type in their new URL, new FTP credentials and new database server credentials. The blog will then be able to use all of those details and move itself over, automatically. I’m not a UI designer so please forgive my mock-up:</p>

<p><img src="http://gsoc2010.files.wordpress.com/2010/05/migrate_sceenshot.png" alt="" title="" /></p>

<p>I’ll be posting a revised project proposal to this blog soon. It will be at the following URL when it’s ready:</p>

<p><a href="http://gsoc2010.wordpress.com/brian-mckenna-automatic-migration/">http://gsoc2010.wordpress.com/brian-mckenna-automatic-migration/</a></p>

<p>This has been a brief overview of my project. What do you think of the idea? What would you like to see implemented?</p>]]></content></entry><entry><id>http://brianmckenna.org/blog/pyweek_2010</id><title>PyWeek 2010</title><published>2010-04-29T00:00:00Z</published><updated>2010-04-29T00:00:00Z</updated><link href="http://brianmckenna.org/blog/pyweek_2010" /><author><name>Brian McKenna</name></author><content type="html"><![CDATA[<p>At the beginning of the month I was finishing off a little game I helped make for <a href="http://www.pyweek.org/">PyWeek</a>. PyWeek is a game programming competition where you must create a whole game within a week and use Python.</p>

<p>I was the sole programmer on the team, there were two other people working on art and music. I was really happy with the end product (even though it was rushed). The reviews of our game <a href="http://www.pyweek.org/e/blank_page/ratings/">are public</a>, here are a few choice ones:</p>

<p>Anonymous:</p>

<blockquote>
  <p>Excellent concept. Hard and tricky game - had to think to get through this game (that's good) and it doesn't repeat "puzzles" much. Well executed, the jumping/bouncing feels nice and bouncy. Great graphics and nice music. Intro video was neat, although I think it could've taken the whole screen. Excellent work on this game, I just wish it was longer. You should really give some thought into making this a full game, with more levels, a tutorial, a better storyline and everything (maybe some new features would be nice too, like different types of jelly). I really think it has potential for a great "full game". :)</p>
</blockquote>

<p>Anonymous:</p>

<blockquote>
  <p>I was extremely impressed by this entry! Great job! However, the learning curve level was way too hard for me to really enjoy it. If there were more tutorial parts and less mid-air precision shots, I would have had a lot of fun with it.</p>
</blockquote>

<p>Anonymous:</p>

<blockquote>
  <p>Retro look. Platforming with jelly bouncing. What's not to like? Apart from the fact that I ran out of goo that is.</p>
</blockquote>

<p>Anonymous:</p>

<blockquote>
  <p>I was amazed by the production values of this game. Really cool art style.
  The gameplay is nice... but i couldn't figure out how to cross beyond the first obstacle :(</p>
</blockquote>

<p>I've posted some videos of the game to YouTube:</p>

<p><a href="http://www.youtube.com/watch?v=Pxsv6aG3En4">
<img src="http://i1.ytimg.com/vi/Pxsv6aG3En4/0.jpg" alt="" title="" />
</a></p>

<p><a href="http://www.youtube.com/watch?v=i5pGKABDgx4">
<img src="http://i1.ytimg.com/vi/i5pGKABDgx4/0.jpg" alt="" title="" />
</a></p>

<p><a href="http://www.youtube.com/watch?v=ukPlFI9kCF8">
<img src="http://i1.ytimg.com/vi/ukPlFI9kCF8/0.jpg" alt="" title="" />
</a></p>

<p>I have created a <a href="http://brianmckenna.org/files/blank_page-1.0-py2exe.zip">Windows package</a> for anyone who wants to try it out. There is also a <a href="http://media.pyweek.org/dl/10/blank_page/blank_page-1.0.zip">Python source version</a> for people on other systems - the only problem is that the source version requires <a href="http://www.pyglet.org/">Pyglet</a>.</p>

<p>I'm planning on working on this game a bit further and entering into the <a href="http://pyggy.pyweek.org/">Pyggy Awards</a>.</p>]]></content></entry><entry><id>http://brianmckenna.org/blog/javascript_as_a_functional_language</id><title>JavaScript as a Functional Language</title><published>2010-04-28T00:00:00Z</published><updated>2010-04-28T00:00:00Z</updated><link href="http://brianmckenna.org/blog/javascript_as_a_functional_language" /><author><name>Brian McKenna</name></author><content type="html"><![CDATA[<p><em>This post has been modified from an <a href="http://stackoverflow.com/questions/2677532/how-is-a-functional-programming-based-javascript-app-laid-out/2695594#2695594">answer I posted on Stack Overflow</a>.</em></p>

<p>A lot of people <a href="http://javascript.crockford.com/javascript.html">misunderstand JavaScript</a>, possibly because its syntax looks like most other programming languages (where Lisp/Haskell/OCaml behave and look completely different).</p>

<p>JavaScript is sometimes called object-oriented. It is a loosely-typed dynamic language and doesn't have classes nor classical inheritance. This means that when JavaScript is compared to Java or C++, the concepts just don't match up.</p>

<p>I find that JavaScript can be better compared to a Lisp; it has closures and first-class functions. Using them you can create other functional programming techniques, such as <a href="http://ejohn.org/blog/partial-functions-in-javascript/">partial application</a> (currying).</p>

<p>Today's aim is to make a piece of JavaScript act more functional. Let's take an example (using <code>sys.puts</code> from node.js):</p>

<pre><code>var external;
function foo() {
    external = Math.random() * 1000;
}
foo();

sys.puts(external);
</code></pre>

<p>To get rid of global side effects, we can wrap it in a closure:</p>

<pre><code>(function() {
    var external;
    function foo() {
        external = Math.random() * 1000;
    }
    foo();

    sys.puts(external);
})();
</code></pre>

<p>Notice that we can't actually do anything with <code>external</code> or <code>foo</code> outside of the scope. They're completely wrapped up in their own closure, untouchable.</p>

<p>Now, to get rid of the <code>external</code> side-effect:</p>

<pre><code>(function() {
    function foo() {
        return Math.random() * 1000;
    }

    sys.puts(foo());
})();
</code></pre>

<p>That's as far as we'll get. In the end, the example is not purely-functional because it <strong>can't</strong> be. Using a random number reads from the global state (to get a seed) and printing to the console is a side-effect.</p>

<p>I also want to point out that mixing functional programming with objects is perfectly fine. Take this for example:</p>

<pre><code>var Square = function(x, y, w, h) {
   this.x = x;
   this.y = y;
   this.w = w;
   this.h = h;
};

function getArea(square) {
    return square.w * square.h;
}

function sum(values) {
    var total = 0;

    values.forEach(function(value) {
        total += value;
    });

    return total;
}

sys.puts(sum([new Square(0, 0, 10, 10), new Square(5, 2, 30, 50), new Square(100, 40, 20, 19)].map(function(square) {
    return getArea(square);
})));
</code></pre>

<p>Some Lisps even have things called property lists which can be thought of as objects.</p>

<p>The real trick to using objects in a functional style is to make sure that you don't rely on their side effects but instead treat them as immutable. An easy way is whenever you want to change a property, just create a <em>new</em> object with the new details and pass that one along, instead (this is the approach often used in Clojure and Haskell).</p>

<p>I strongly believe that functional aspects can be very useful in JavaScript but ultimately, you should use whatever makes the code more readable and what works for <strong>you</strong>.</p>]]></content></entry><entry><id>http://brianmckenna.org/blog/nodejs_via_cgi</id><title>node.js via CGI</title><published>2010-04-27T00:00:00Z</published><updated>2010-04-27T00:00:00Z</updated><link href="http://brianmckenna.org/blog/nodejs_via_cgi" /><author><name>Brian McKenna</name></author><content type="html"><![CDATA[<p>Hi everyone! I've decided to create a new blog for myself. As many programmers do, I used this blog as an excuse to learn a new platform.</p>

<p>I wrote this blog engine from scratch using <a href="http://nodejs.org/">node.js</a>. What makes this site different to the others running node.js is that this one is running completely off of a shared server (<a href="http://dreamhost.com/">DreamHost</a>, specifically).</p>

<p>When I was looking into using node.js, I found that most developers are deploying it by using the built-in web server and then optionally proxying it to Apache or Nginx. Those options just aren't possible when using cheap shared hosting. At this point I could:</p>

<ol>
<li>Rent a virtual machine to deploy a node.js website (costs money)</li>
<li>Hack up a custom solution to make node.js server on a shared server (takes time)</li>
</ol>

<p>I chose the latter and now I am the proud creator of the <a href="http://github.com/pufuwozu/node-cgi">node-cgi</a> monster. It's a CGI adaptor for node.js that mimmicks the node.js <code>http</code> library.</p>

<p>To use the adaptor you must create a <code>.htaccess</code> file that redirects paths to a CGI script. This blog uses:</p>

<pre><code>Options +ExecCGI
AddHandler cgi-script cgi

RewriteEngine on
RewriteCond %{REQUEST_FILENAME} !-f
RewriteRule (.*) server.cgi
</code></pre>

<p>Where server.cgi contains:</p>

<pre><code>#!/usr/bin/env node

var blog = require('./blog'),
    cgi = require('./cgi');

var server = cgi.createServer(blog.requestListener);
server.listen();
</code></pre>

<p>For people not familiar with node.js, using this library is very similar to the standard way of creating a HTTP server:</p>

<pre><code>var blog = require('./blog'),
    http = require('http');

var server = http.createServer(exports.requestListener);
server.listen(5000, "localhost");
</code></pre>

<p>This means that some applications will only have to change <code>require('http')</code> to <code>require('cgi')</code> to create a CGI version!</p>

<p>The library is <a href="http://github.com/pufuwozu/node-cgi">up on GitHub</a> for those that want to take a look. I'd like to know if anyone finds it useful!</p>

<script type="text/javascript">
var disqus_identifier = 'nodejs_via_cgi';
</script>]]></content></entry></feed>
