Bluish Coder

Programming Languages, Martials Arts and Computers. The Weblog of Chris Double.


2006-06-05

Javascript 1.7

It looks like Javascript 1.7 is getting some interesting new features. Brendan Eich did a presentation about what is being added and changed.

One that looks useful for the concurrency things I'm playing with is destructuring assignment:

var [a, b, c] = [ 'one', 'two', 'three' ];

This would make breaking apart messages received from processes a bit easier.

Interestingly Javascript 1.7 has Python style generators. These have been used in Python to build lightweight threads so it looks like it'll be possible to do the threading described in my previous posts natively one day.

This document describes how to build pre-release versions of the Javascript shell to play with this.

Tags: javascript 

2006-06-05

More concurrency in Narrative Javascript

I've added to my lightweight threading example in Narrative Javascript to include support for sending and receiving messages between processes. The style of communication is based on the Erlang style of concurrency whereby processes communicate by sending messages. The threads2 example is here.

This page has two processes running on it. They start when the page loads. Both processes block immediately waiting for a message. When the message is received the append the text of the message to a textarea on the page:

function t1() {
  while(true) {
    var msg = receive->();
    var dest = document.getElementById("p2");
    dest.value += (msg +"\n");
  }
}

The 'receive' call blocks immediately if there are no messages in the processes mailbox. If a message arrives it unblocks and continues. It must be called as an asynchronous operation using the '->' operator for this to work. Processes are started using 'spawn':

var process1 = spawn(t1);
var process2 = spawn(t2);

Messages can be sent from one process to another using 'send'. This is also an asynchroous operation and must use the '->' operator. Here's the code that is run when a button is pressed:

function send1() {
  spawn(function() {
    var msg = document.getElementById('msg1').value;
    send->(process1, msg);
  });
}

It spawns a process which obtains the text from the text input area and sends it to one of the processes. This will cause that process to unblock and continue from the 'receive' call.

The updated code is:

Some ideas for things that would be nice to add or build upon:

  • Provide the equivalent of Termite's '!?' operator to allow sending a message and waiting for a reply to that message.
  • Use a persistent connection (ie. Comet) to an Erlang server and allow messages to be sent back and forth from Erlang processes and Narrative Javascript processes.
  • Add futures and promises allowing dataflow style programming.

Note that this code is just 'playing around' code and is not intended to be robust or production ready. I'm just exploring how these ideas that have traditionally been used on the server work in a client side browser based language.

Tags: javascript 

2006-06-04

Partial Continuations and Narrative Javascript

I've been playing with Narrative Javascript and decided to have a go at porting the bshift and breset Scheme example to it. I'd previously had a go at this with Rhino.

Trying some simple examples out it turns out that the continuations provided by Narrative Javascript are really partial continuations. Here's an example demonstrating this:

var ex4cc ;

function ex4a(cont) {
  ex4cc = cont;
  cont();

}

function ex4() {
  var x = 0;
  ex4a->();
  x = x +1;
  print("here:" + x);
  return x;

}

function callex4() {
  var x = ex4cc();
  print("Returned: "+ x);

}

js> ex4()
here:1
js> ex4cc()
here:2
js> ex4cc()
here:3
js> callex4()
here:4
Returned: undefined

Full continuations don't return to their caller since they effectively replace the entire call stack with the original call stack of the continuation. This example shows 'callex4' printing 'Returned...' after the original continuation was called. The partial continuation appears to be delimited by the nearest function in the call stack which was not called with the '->' operator. This makes a simple shift/reset something like this:

function reset(f) {
  return f();

}

function shift(f, cont) {
  f(cont);
}

The 'range' function and examples:

function range(from, to) {
   return  shift->(function(pcc) {
               while(from < to) {
                 pcc(from++);
               }
               return to;
             });
} 

function test1() {
  reset(function() {
    print(range->(1, 5));
  });

}

function test2() {
  var sum = 0;
  reset(function() {
          sum += range->(1, 10);
        });
  print(sum);

}

js> test1()
1
2
3
4
5

js> test2()
55 

Once compiled with Narrative Javascript's compiler the resulting code runs fine in a standard web browser.

Neil Mix, the author of Narrative Javascript, has set up a google group for discussion about it.

Tags: continuations 

2006-06-04

Narrative Javascript

Narrative Javascript extends the Javascript language to include a new operator. That operator allows writing procedural looking code that spans asynchronous operations.

Very much like continuations enable writing web applications such that you don't need to break application flow to model the HTTP protocol, Narrative Javascript enables you to write your code in a sequential style and have it automatically produce the callbacks and handlers for events, XMLHttpRequest, etc.

It consists of a compiler that compiles a Javascript plus the new operator into standard Javascript which can be included in the web page.

Narrative JavaScript consists of a compiler and a runtime library. You write your code code as Narrative JavaScript (using the blocking operator) and the compiler will parse and translate the code into regular (asynchronous) JavaScript. You then deploy the compiled code along with a runtime library. To aid in debugging, the compiler keeps line numbering of the source code intact in the compiled code.

An example from the website shows this code:

function startForm() {
        displayPage1();
    }

    function onPage1Submit() {
        var errors = validatePage1Input();
        if(errors) {
            displayPage1(errors);
        } else {
            displayPage2();
        }
    }

    function onPage2Submit() {
        var errors = validatePage2Input();
        if(errors) {
            displayPage2(errors);
            return;
        }

        var url = buildUrl();
        doHttpRequest(url, handleResponse);
    }

    function handleResponse(r) {
        if (r.page1Errors) {
            displayPage1(r.page1Errors);
        } else if (r.page2Errors) {
            displayPage2(r.page2Errors);
        } else {
            displaySuccess();
        }
    }

Written in Narrative Javascript as:

function displayForm() {
    var page1Errors = [];
    var page2Errors = [];
    var success = false;

    while (!success) {
        while (page1Errors) {
            page1Errors = displayPage1->(page1Errors);
        }

        while (page2Errors) {
            page2Errors = displayPage2->(page2Errors);
        }

        var url = buildUrl();
        var response = doHttpRequest->(url);

        page1Errors = r.page1Errors;
        page2Errors = r.page2Errors;
        success = !(page1Errors || page2Errors);
    }

    displaySuccess();
}

Notice the code in the following line:

var response = doHttpRequest->(url);

This does an XMLHttpRequest which usually requires having a callback function process the request. This is done automatically by Narrative Javascript. From the sounds of it it compiles the code into CPS form and uses the continuation as the callback. This enables the code to continue from where it left off. In this case returning the value of the XMLHttpRequest and continuing the function.

Any operation that requires a callback function is a candidate for blocking. Please note that blocking does not mean that the entire JavaScript runtime locks up waiting for an operation to finish. Instead, Narrative JavaScript makes use of co-operative multitasking. When you use the blocking operator, you are yielding control to the JavaScript runtime to execute other operations until your operation has yielded a return value.

This system looks very nice and I look forward to playing with it.

Tags: javascript 

2006-06-02

Hop - Web Application System

Hop is an interesting web application system that appears to be similar in terms of goals to Links. From the website:

Hop is a new higher-order language designed for programming interactive web applications such as web agendas, web galleries, music players, etc. It exposes a programming model based on two computation levels. The first one is in charge of executing the logic of an application while the second one is in charge of executing the graphical user interface. Hop separates the logic and the graphical user interface but it packages them together and it supports strong collaborations between the two engines. The two execution flows communicate through function calls and event loops. Both ends can initiate communications.

It seems to be implemented in Bigloo Scheme and the demo's look very nice.

Tags: ajax 


This site is accessable over tor as hidden service 6vp5u25g4izec5c37wv52skvecikld6kysvsivnl6sdg6q7wy25lixad.onion, or Freenet using key:
USK@1ORdIvjL2H1bZblJcP8hu2LjjKtVB-rVzp8mLty~5N4,8hL85otZBbq0geDsSKkBK4sKESL2SrNVecFZz9NxGVQ,AQACAAE/bluishcoder/-61/


Tags

Archives
Links