return page history
α-wwwiki
::
history/dipert/20130622-205015.txt
editor : alpha [82.255.2.48] 2013/06/22 20:50:15 _h2 15 lines for a very small lisp _p A very small lisp interpreter written in 15 lines. Code adapted from [[Alan Dipert|http://alan.dipert.org/post/7193534410/discover-lisp-in-your-web-browser-with-javascript]] who gives a very clean and clear explanation about the lisp fundamental principle. _ul copy a line from the examples, _ul paste it into the field below, _ul click on the button "evaluate". {input {@ id="input" type="texte" value="['Math.sqrt', ['+', ['*',3,3], ['*',4,4]]]" style="width:100%; font:normal 1em courier; color:red;" }} {input {@ type="submit" value="evaluate" onclick="°° // LISP CODE START : var operators = {'+':'+', '-':'-', '*':'*', '/':'/'}; // the basic dictionary var evaluate = function(expression) { // ['*',1,2,3,4,5,6] , ['Math.sqrt', 2] or ['+', ['*',3,3], ['*',4,4]] if (!Array.isArray(expression)) return expression.toString(); var func_name = expression[0]; // * , Math.sqrt var func_args = expression.slice(1); // [1, 2, 3, 4, 5, 6] , or [2] var compiled_args = []; for (var i=0; i< func_args.length; i++) compiled_args.push( evaluate( func_args[i] ) ); // ['1', '2', '3', '4', '5', '6'] or ['2'] , ['3*3', '4*4'] if (operators.hasOwnProperty(func_name)) // it's in the dictionary return compiled_args.join(func_name); // 1*2*3*4*5*6 else // it's a JS math function return func_name + '(' + compiled_args.join(',') + ')'; // Math.sqrt(2) } function do_evaluate(input) { return eval(evaluate(eval(input))); } // LISP CODE END getId('output').innerHTML = do_evaluate(getId('input').value); °°"}} {pre {@ id="output"}} _h3 examples {pre ['+',1,2,3,4,5,6] ['*',1,2,3,4,5,6] ['+', ['*',3,3], ['*',4,4]] ['Math.sqrt', 2] ['Math.pow',2,8] ['Math.sqrt', ['+', ['*',3,3], ['*',4,4]]] And try new ones ... } _h3 lisp code {pre °° var operators = {'+':'+', '-':'-', '*':'*', '/':'/'}; var evaluate = function(expression) { if (!Array.isArray(expression)) return expression.toString(); var func_name = expression[0]; var func_args = expression.slice(1); var compiled_args = []; for (var i=0; i< func_args.length; i++) compiled_args.push( evaluate( func_args[i] ) ); if (operators.hasOwnProperty(func_name)) return compiled_args.join(func_name); else return func_name + '(' + compiled_args.join(',') + ')'; } function do_evaluate(input) { return eval(evaluate(eval(input))); } °°}