Here's a condenced retrace of his steps using F# and Pencil.Unit
Step 1) Write Micro Unit Test
Theory "Fib should work for known values from Wikipedia"
[(0,0); (1, 1); (2, 1); (3, 2); (20, 6765)]
(fun (n, e) -> Fib n |> Should Equal e)
Step 2) Implement Fib
[(0,0); (1, 1); (2, 1); (3, 2); (20, 6765)]
(fun (n, e) -> Fib n |> Should Equal e)
let rec Fib = function
| 0 -> 0
| 1 -> 1
| _ as n -> Fib(n - 1) + Fib(n - 2)
Step 3) Theorize about FastFib
| 0 -> 0
| 1 -> 1
| _ as n -> Fib(n - 1) + Fib(n - 2)
Theory "FastFib should give same result as Fib"
[0; 1; 2; 3; 25]
(fun n -> FastFib n |> Should Equal (Fib n))
Step 4)Implement FastFib
[0; 1; 2; 3; 25]
(fun n -> FastFib n |> Should Equal (Fib n))
let FastFib n =
let rec loop n a b =
match n with
| 0 -> a
| _ -> loop (n - 1) b (a + b)
loop n 0 1
let rec loop n a b =
match n with
| 0 -> a
| _ -> loop (n - 1) b (a + b)
loop n 0 1
No comments:
Post a Comment