Skip to content

Commit

Permalink
Added factorial program
Browse files Browse the repository at this point in the history
  • Loading branch information
amitayh committed Aug 20, 2015
1 parent 10f9c7b commit 62f504a
Show file tree
Hide file tree
Showing 2 changed files with 23 additions and 5 deletions.
24 changes: 20 additions & 4 deletions specs/lisp-spec.js
Original file line number Diff line number Diff line change
Expand Up @@ -131,14 +131,12 @@ describe('lispjs', function () {
});

describe('programs tests', function () {
it('should be able to calculate fibonacci recursively', function () {
it('should calculate fibonacci recursively', function () {
var prog =
['define', 'fib',
['lambda', ['n'],
['if', ['<', 'n', 2],
// n < 2, return 1
1,
// return fib(n-1) + fib(n-2)
['+',
['fib', ['-', 'n', 1]],
['fib', ['-', 'n', 2]]]]]];
Expand All @@ -153,7 +151,25 @@ describe('lispjs', function () {
assert.equal(lisp.getResult(['fib', 5], fibEnv), 8);
});

it('should be able to define map function with default env', function () {
it('should calculate factorial recursively', function () {
var prog =
['define', 'fact',
['lambda', ['n'],
['if', ['<', 'n', 2],
1,
['*', 'n', ['fact', ['-', 'n', 1]]]]]];

var factEnv = lisp.evaluate(prog, lisp.defaultEnv)[1];

assert.equal(lisp.getResult(['fact', 0], factEnv), 1);
assert.equal(lisp.getResult(['fact', 1], factEnv), 1);
assert.equal(lisp.getResult(['fact', 2], factEnv), 2);
assert.equal(lisp.getResult(['fact', 3], factEnv), 6);
assert.equal(lisp.getResult(['fact', 4], factEnv), 24);
assert.equal(lisp.getResult(['fact', 5], factEnv), 120);
});

it('should support higher order functions (map)', function () {
var prog = [
// Define map function
['define', 'map',
Expand Down
4 changes: 3 additions & 1 deletion src/lisp.js
Original file line number Diff line number Diff line change
Expand Up @@ -71,10 +71,12 @@ function copy(obj) {

var defaultEnv = {
'<': function (a, b) { return a < b; },
'>': function (a, b) { return a < b; },
'>': function (a, b) { return a > b; },
'=': function (a, b) { return a == b; },
'+': function (a, b) { return a + b; },
'-': function (a, b) { return a - b; },
'*': function (a, b) { return a * b; },
'/': function (a, b) { return a / b; },
car: function (xs) { return xs[0]; },
cdr: function (xs) { return xs.slice(1); },
cons: function (x, xs) { return [x].concat(xs); },
Expand Down

0 comments on commit 62f504a

Please sign in to comment.