Pages

2011年5月28日土曜日

Coffee Script 最初の一杯

coffee scriptを試してみる。
Coffee Scriptは、文法がPythonに似ている言語で、コンパイルするとjavascriptを生成する。
恐らく、javascriptの強力な部分を活かし、判りにくい部分を隠ぺいしたモダンな開発言語を作成することが目的なのだと思う。javascriptベースのサーバサイド実行環境node.jsなど、javascriptだけでアプリケーションを開発する環境が整ってきている。javascriptは、インターネット・アプリケーション開発で、その言語の強力さとブラウザが実行エンジンを持つことから、重要な位置を占めてきた。サーバサイドが全てjavascriptで作成できれば、一つの言語でクライアントサイド、サーバサイドを共に開発することが出来る。しかし、ロジックを記述したり、トランザクションを記述するには、正直判りにくいと思う。coffee scriptは、そのようなニーズから生まれたのではないか。

Coffee Scriptとは
Coffee Scriptは、小規模な言語であり、コンパイルしてJavaScriptを生成する。中括弧やセミコロンに幻惑されて気づかないが、JavaScriptはいつも、その内に素晴らしいオブジェクトモデルを隠し持っている。Coffee Scriptは、JavaScriptの、その良い部分をシンプルな方法で顕在化する試みである。

CoffeeScriptの黄金律は、「まさにそれはJavascriptだ」と言うこと。コードはJavaScriptに一対一でコンパイルされ、実行時に不要な処理が行われることはない。専用のライブラリは不要だ。コンパイルされたJavaScriptコードは、読みやすく 警告なし、注釈なしで、全てのJavascript実行環境で動作するし、多くの場合、手書きのコードと同等か早く動作するでしょう。

CoffeeScript is a little language that compiles into JavaScript. Underneath all of those embarrassing braces and semicolons, JavaScript has always had a gorgeous object model at its heart. CoffeeScript is an attempt to expose the good parts of JavaScript in a simple way.

The golden rule of CoffeeScript is: "It's just JavaScript". The code compiles one-to-one into the equivalent JS, and there is no interpretation at runtime. You can use any existing JavaScript library seamlessly (and vice-versa). The compiled output is readable and pretty-printed, passes through JavaScript Lint without warnings, will work in every JavaScript implementation, and tends to run as fast or faster than the equivalent handwritten JavaScript.
(Coffee script ホームページから 引用)

最初のサンプルをコンパイルしてみる。
  1. # ファイル square.coffee  
  2. square = (x) -> x * x         # 無名関数"(x) -> x * x"を値にもつ。つまり関数名がsquare。  
  3. cube = (x) -> square(x) * x   # カリー化?みたいな感じ?  
  4. alert cube(5)                 # htmlでウインドウを表示させる。  
# ファイル square.coffee
square = (x) -> x * x         # 無名関数"(x) -> x * x"を値にもつ。つまり関数名がsquare。
cube = (x) -> square(x) * x   # カリー化?みたいな感じ?
alert cube(5)                 # htmlでウインドウを表示させる。

$ vim square.coffee
$ coffee -c square.coffee
$ ls 
square.coffee square.js

コンパイルした結果(square.js)を見てみると
  1. (function() {  
  2.   var cube, square;  
  3.   square = function(x) {  
  4.     return x * x;  
  5.   };  
  6.   cube = function(x) {  
  7.     return square(x) * x;  
  8.   };  
  9.   alert(cube(5));  
  10. }).call(this);  
(function() {
  var cube, square;
  square = function(x) {
    return x * x;
  };
  cube = function(x) {
    return square(x) * x;
  };
  alert(cube(5));
}).call(this);

実際に実行させてみる。以下のようなテスト用ソースを用意した。
実行結果はここで

0 件のコメント:

コメントを投稿