Bug 7646 – bug in code sample and unittest

Status
RESOLVED
Resolution
INVALID
Severity
trivial
Priority
P5
Component
dlang.org
Product
D
Version
D2
Platform
All
OS
All
Creation time
2012-03-04T11:59:00Z
Last change time
2012-06-04T07:16:19Z
Assigned to
nobody
Creator
josvanuden

Comments

Comment #0 by josvanuden — 2012-03-04T11:59:48Z
The following sample code on std.functional contains a bug. http://dlang.org/phobos/std_functional.html#memoize ulong fib(ulong n) { alias memoize!fib mfib; return n < 2 ? 1 : mfib(n - 2) + mfib(n - 1); } assert(fib(10) == 89); fib(10) should be 55. http://en.wikipedia.org/wiki/Fibonacci_number#List_of_Fibonacci_numbers I think the code should be (n <= 2): ulong fib(ulong n) { alias memoize!fib mfib; return n <= 2 ? 1 : mfib(n - 2) + mfib(n - 1); } assert(fib(10) == 55); It's also in the unittest https://github.com/D-Programming-Language/phobos/blob/master/std/functional.d
Comment #1 by josvanuden — 2012-03-04T12:08:27Z
(In reply to comment #0) > I think the code should be (n <= 2): > > ulong fib(ulong n) { > alias memoize!fib mfib; > return n <= 2 ? 1 : mfib(n - 2) + mfib(n - 1); > } > > assert(fib(10) == 55); No, that still won't do. This is better: ulong fib(ulong n) { alias memoize!fib mfib; return n <= 2 ? n != 0 : mfib(n - 2) + mfib(n - 1); }
Comment #2 by josvanuden — 2012-03-11T04:24:44Z
ulong fib (ulong n) { alias memoize!fib mfib; return n < 2 ? n : mfib(n - 2) + mfib(n - 1); }
Comment #3 by josvanuden — 2012-06-04T07:16:19Z
It turns out some people regard F0 = 0 and some F0 = 1. So it's not a bug after all.