lazy.js icon indicating copy to clipboard operation
lazy.js copied to clipboard

Feature Idea: `generate` automatically holds a sequence(array) in closure

Open ken-okabe opened this issue 10 years ago • 2 comments

Great job as usual. Thanks daniel tao. I have a thought of new feature.

IMO, your fibonacci sample is hard to follow.

The reason is

  1. We need to implement closure to pass the proper function to generate.
  2. You just use too many variables, such as x, y,prev.
  3. (2) typically occurs when we employ Imperative Programming and try to design algorithm flow. We definitely can and should define a Sequence in Math manner since this is a library for Declarative programming.

So, here's my code:

var _ = require('lazy.js');

var fibF = function()
{
  var seq = []; //build array sequence  in this closure
  var f = function(n)
  {
    var val;
    if (n <= 1)
    {
      val = 1; // as the Fib definition in Math
    }
    else
    {
      val = seq[n - 2] + seq[n - 1];  // as the Fib definition in Math
    }
    seq[n] = val;
    return val;
  };
  return f;
}();

var Fib = _.generate(fibF);

var fib_10 =
  Fib
  .take(10)
  .toArray();

console.log(fib_10); //[ 1, 1, 2, 3, 5, 8, 13, 21, 34, 55 ]

This works, however, I think the code could be much much cleaner like:

var _ = require('lazy.js');

var fibF  = function(n)
{ 
    if (n <= 1)
    {
      return 1; // as the Fib definition in Math
    }
    else
    {
      return _.this(n - 2) + _.this(n - 1);   // as the Fib definition in Math
    } 
}; 

var Fib = _.generate(fibF);

var fib_10 =
  Fib
  .take(10)
  .toArray();

console.log(fib_10); //[ 1, 1, 2, 3, 5, 8, 13, 21, 34, 55 ]

I am looking forward to your thought.

Thanks!

ken-okabe avatar Jun 18 '14 05:06 ken-okabe

:thumbsup:

speigg avatar Jun 18 '14 12:06 speigg

This is harder than I thought.

To make this work for recursive functions such as fibonacci sequence, the only working method I found so far is, to wrap the function by some memoize function at the declaration., like underscore does.

http://underscorejs.org/#memoize

var memoize = require('memoizee');

var fib = memoize(function(n)
{
  if (n <= 1)
  {
    return 1; // as the Fib definition in Math
  }
  else
  {
    return fib(n - 2) + fib(n - 1); // as the Fib definition in Math
  }
});

ken-okabe avatar Jun 30 '14 13:06 ken-okabe