Tuesday 1 February 2011

Week 1 Exercise 3.2 Function greaterThan that returns a function

Write a function greaterThan, which takes one argument, a number, and returns a function that represents a test. When this returned function is called with a single number as argument, it returns a boolean: true if the given number is greater than the number that was used to create the test function, and false otherwise.

On my first attempt I was not what the question was trying to get me to do.

function greaterThan (a){
  function test (y){
    if (a < y) {
      return true;
    }else {
      return false;}
  }
    show (test (50));
  }
  show (greaterThan(3));
 
After reading the solution, it was a bit more clear:

function greaterThan (a){
  return function test (y){
    return y > a;
};   
  }

var greaterThanTen = greaterThan(10);
show (greaterThanTen (9));

The last few parts of chapter two of the book that concerns anonymous function and recursion was more complicated. It requires multiple read through.

No comments:

Post a Comment