Can anyone tell me what is wrong with this F# snippet?
f#, functional-programming, matching
Solution
The last bit is slightly wrong - should be
if m.ContainsKey(i) then
if m.[i] > 0 then
m.[i]
else
let x = fib(i - 1) + fib(i - 2)
m.Add(i, x)
x
You are returning from within the if statement. You probably dont need the `if m.[i] > 0` either. In this case you get
let m = Dictionary<int, int>()
let rec fib i =
match i with
| 1 -> i
| 0 -> i
| _ ->
if m.ContainsKey(i) then
m.[i]
else
let x = fib(i - 1) + fib(i - 2)
m.Add(i, x)
m.[i]
For formatting on Stackoverflow just paste the code in then highlight and press ctrl+k or hit the `{}` button to automatically put the section into code mode (code is indented four spaces past normal text)
Problem
The line before the else statement apparently was expecting a unit but got a boolean instead. I'm just starting out with F# but can't fathom this one. I'm fighting the layout a bit as I've never used Stackoverflow before and the code box is still confusing me! The spacing in the original is indented, I believe, correctly. ``` let m = Dictionary<int, int>() let rec fib i = match i with | 1 -> i | 0 -> i | _ -> if m.ContainsKey(i) then if m.[i] > 0 then m.[i] else let x = fib(i - 1) + fib(i - 2) m.Add(i, x) m.[i] ``` If anyone can tell me how to keep the spacing in these posts I'd be grateful!