getify / Functional-Light-JS

Pragmatic, balanced FP in JavaScript. @FLJSBook on twitter.
http://FLJSBook.com
Other
16.6k stars 1.96k forks source link

Chapter 8: Continuation Passing Style (CPS) Fibonacci code snippet offset 1 #193

Closed deorst closed 4 years ago

deorst commented 4 years ago

If I run the code snippet with the test data of n = 1, 2, 3, 4, 5, 6 I get 1, 1, 2, 3, 5, 8 while the correct results are 0, 1, 1, 2, 3, 5. So something like this might solve the problem: const outer = n => fib(n-1) The other solution is just tweak a base case a bit. So the end result would be:

function fib(n,cont = identity) {
  if (n <= 2) return cont( n-1 );
  return fib(
    n - 2,
    n2 => fib(
      n-1,
      n1 => cont( n2 + n1 )
    )
  );
}
getify commented 4 years ago

fib(1) is 1, not 0.

You may be asking what fib(0) should be (ostensibly, 0), but there's historical disagreement as to whether to include 0 in the sequence.

In any case, if you use the fib(..) implementation in the book, fib(0) == 0, the way it "should" be.