2

I asked a question before about using lazy evaluation in Scala. I was trying to write the following Haskell function in Scala:

fib a b = c : (fib b c)
   where c = a+b

The answer to that question was that I couldn't use Lists, but should rather use Streams. Now I'm trying to do the same thing in Javascript. I translated the function, and tried it on this site:

function fib(a,b) {
    c = a+b;
    return [c] + fib(b,c);
}

var res = fib(0,1).slice(0,10);

console.log(res);

But I get the following error:

RangeError: Maximum call stack size exceeded

Does Javascript have a way to do this?

4

3 回答 3

10

您可以具体化惰性计算正在使用的 thunk(阅读:“尚未评估的继续计算的函数”)。

var fib = function (a, b) {
  var c = a + b
  return { "this": c, "next": function () { return fib(b, c) } }
}

这样

> var x = fib(1,1)
> x.this
2
> x = x.next()
> x.this
3

从某种意义上说,这是一个精确的翻译*,我的返回对象代表一个 Haskell (:)“cons” 单元格。从这里开始编写一个“take”函数来将这个javascript“惰性列表”转换为一个javascript严格数组会相对容易。

这是一个版本。

var take = function(n, cons) {

    var res = []
    var mem = cons

    for (var i = 0; i < n; i++) {
      res.push(mem.this)
      mem = mem.next()
    }

    return res
}

这样

> take(10, fib(1,1))
[2, 3, 5, 8, 13, 21, 34, 55, 89, 144]

(*) 从技术上讲,即使是"this"值也应该包含在一个 thunk 中,但我采用了列表的严格概念,这通常非常接近每个人的直觉。

于 2013-06-26T21:30:31.133 回答
2

不完全是 Haskell 惰性求值,但你可以用柯里化做类似的事情。

function fib(a,b) {
    var first = true;

    return function(n) {
        if (!isFinite(n) || n < 0)
            throw "Invalid argument";

        var result = first ? [a,b] : [];
        first = false;

        for (var i = result.length; i < n; i++)
            result.push(b = a+(a=b));

        return result;
    };
}

可以多次调用返回的函数以获得连续的结果:

var f = fib(0,1); // Initialize the sequence with starting values

// Invoke the resulting function with the number of results you want
console.log(f(10)); // [0, 1, 1, 2, 3, 5, 8, 13, 21, 34]

console.log(f(4));  // [55, 89, 144, 233]

console.log(f(4));  // [377, 610, 987, 1597]
于 2013-06-26T20:24:45.243 回答
0

ES6 具有生成器函数,您可以将其用于惰性求值(与解构赋值运算符结合使用)使用这种技术,我们可以编写如下所示的斐波那契函数(只是另一种方法)。

var fib_generator = function *(){
  var current = 0, next = 1;
  while(true)
  {
     [next, current] = [next+current, next];
     yield current;
  }
}

var fib = fib_generator();


// below is the sample code prints values uptill 55
for(var i=0; i<10; i++)
{
   console.log(fib.next().value);
}

于 2016-11-26T12:55:05.917 回答