return page history
α-wwwiki
::
history/psil/20130619-110423.txt
editor : alpha [83.158.149.135] 2013/06/19 11:04:23 _h1 psil _p I just discover a smart code found on Github : [[psil|https://gist.github.com/pabloPXL/1679611]]. Written by [[Pablo Vidal|https://github.com/pabloPXL]]. {pre {@ id="output"}} {input {@ type="submit" value="psil" onclick="°° // start parser function extcx(ar,cx){ return ar.reduce(function(o, kv){ o[kv[0]] = kv[1]; return o; },cx || {}) } function zip(ar1, ar2){ return ar1.reduce(function(ar, v1, i1){ if (ar2[i1]) ar.push([v1,ar2[i1]]); return ar; },[]) } function atomp(a){ return !(typeof a in {object:0,array:0}) } function lazyp(a){ return (a in {cond:0,quote:0,lambda:0}) } // start dictionary / global environment function env(){ var inst = this; inst.atom = function(a){ return atomp(a) }; inst.set = function(as){ return inst[as[0]] = as[1] }; inst.quote = function(as){ return as[0] }; inst.fst = function(as){ return as[0][0] }; inst.rst = function(as){ return as[0].slice(1) }; inst.cons = function(as){ return [as[0]].concat(as[1]) }; inst.eq = function(as){ return as[0] === as[1] }; inst.cond = function(as,cx){ return leval(as[0],cx) ? leval(as[1],cx) : leval(as[2],cx) }; inst['*'] = function(as){ for (var i=0, p=1; i< as.length; i++) p *= as[i]; return p; }; return inst; } // end dictionary / global environment function apply(rf, as, cx){ return rf in cx && cx[rf].call ? cx[rf].call(null, as, cx) : leval( cx[rf][2], extcx(zip(cx[rf][1], as), cx) ); } function leval(sx, cx){ if (atomp(sx)) return sx in cx ? cx[sx] : sx; var rf = sx[0], as = sx.slice(1).map( function(a){ return lazyp(rf) ? a : leval(a, cx) }); return apply(rf, as, cx); } // end parser // start test function psil () { var cx = new env; var str = '' + '\n' + leval(['set','a',42],cx) + '\n' + leval('a',cx) + '\n' + leval(['eq',42,'a'],cx) + '\n' + leval(['quote',[1,2]],cx) + '\n' + leval(['fst',['quote',[1,2]]],cx) + '\n' + leval(['rst',['quote',[1,2]]],cx) + '\n' + leval(['cons',1,['quote',[2,3]]],cx) + '\n' + leval(['cond',['eq',1,2],42,43],cx) + '\n' + leval(['atom',['quote',[1,2]]],cx) + '\n' + '\nsecond : ' + leval( ['set','second',['quote',['lambda',['x'],['fst',['rst','x']]]]],cx ) + '\n[second,[quote,[1,2,3]]] : ' + leval(['second',['quote',[1,2,3]]],cx) + '\n' + '\n[*,1,2,3,4,5,6] : ' + leval(['*',1,2,3,4,5,6],cx) + '\ncubic : ' + leval( ['set','cubic',['quote',['lambda',['x'],['*','x','x','x']]]],cx) + '\n[cubic,4] : ' + leval(['cubic',4],cx) return str; } getId('output').innerHTML = psil(); °°"}} _p I love it. A lot to learn. More to come ...