Search code examples
javascriptrecursionfunctional-programmingschemesicp

Stuck SICP Exercise 1.1.7 in Javascript


I've decided to try working through the MIT SICP course, but in Javascript.

The following code outputs undefined, but it should output a fairly accurate guess of the square root of 5.

I've tested all of the smaller functions and they all work as expected, the problem must be somewhere in the recursive guessRoot() function, but I can't seem to see the problem.

var square = function(x) {
    return x * x;
};
var abs = function(x) {
    return x > 0 ? x : -x;
};
var goodEnough = function(g, x) {
    return abs(square(g) - x) < 0.01;
};
var average = function(x, y) {
    return (x + y) / 2;
};
var improve = function(g, x) {
    return average(g, (x / g));
};
var guessRoot = function(guess, x) {
    if (goodEnough(guess, x)) {
        return guess;
    } else {
        guessRoot(improve(guess, x), x);
    }
};
console.log(guessRoot(2.5, 5));

Solution

  • Looks like you're just missing a return in the recursive step.

    var guessRoot = function(guess, x) {
        if (goodEnough(guess, x)) {
            return guess;
        } else {
            return guessRoot(improve(guess, x), x); // ... here
        }
    };
    

    http://jsfiddle.net/mattball/TyLsL