Return Styles: Pseud0ch, Terminal, Valhalla, NES, Geocities, Blue Moon. Entire thread

Nomads. Javascript Nomads

Name: Anonymous 2008-04-12 21:42

So I was thinking of writing a simple parser in Javascript. Then decided a simple combinator a la Parsec could be good. Had a little fiddle:


/* State monad in Haskell */

// Simple tuple                                                                                                                                               
function tuple(x,y) { return function(f) { return f(x,y); } }
function fst(t) { return t(function(x,y) { return x; }); }
function snd(t) { return t(function(x,y) { return y; }); }

// Monadic operations                                                                                                                                         

// Equvilent to >>=                                                                                                                                           
function bindM(m,k)                                                                                                      
{  
    return function (s) {                                                                                                                       
        tmp = m(s);
        a = fst(tmp); s_ = snd(tmp);
        return k(a)(s_);
    }
}

// Equvilent to >>                                                                                                                                            
function thenM(m,k) {
    return bindM(m,function(_){return k;});
}

function returnM(v) {                                                                                                                         
    return function (s) {                                                                                                                       
        return tuple(v,s);
    }
}

function evalS(m,s) {
    return fst(m(s));
}

function getS(s) {
    return tuple(s,s);
}

function putS(s) {
    return function(_) {
        return tuple(null,s);
    }
}

/* Simple examples: */
alert(
    evalS(
        thenM( putS("Woo!") , bindM( getS , returnM ) )
        ,2));

alert(
    evalS(
        thenM( putS("Woo!") , getS )
        ,2));


But then I decided a parser like that would probably be as slow as shit. I'll still probably implement it, though. Good fun.

Name: Anonymous 2008-04-12 21:48

Equvilent

Newer Posts
Don't change these.
Name: Email:
Entire Thread Thread List