I am learning F#, and I came across an intellisense error
let rec fib n =
match n with
| 1 -> 1
| 2 -> 2
| _ -> fib(n-1) + fib(n-2)
fib 6 <-- This line says "This expression should have type 'unit', but has type 'int'
Does anyone know how I fix this?
-
If you're typing that code into an interactive console, you'd expect it to print out the answer. But in a program, you'd need to write a line of code that does something with the value returned by your
fibfunction. Either give the result a name, or write it to the console (which would have the typeunit, i.e. "action with no return value"), or something like that.Unknown : Oh ok, for some reason I thought unit said uint. -
I thought I might add that you are defining your fibonacci recurrance incorrectly. Take a look here at your code:
let rec fib n = match n with | 1 -> 1 | 2 -> 2 | _ -> fib(n-1) + fib(n-2);;Now lets map this function over a list:
[0 .. 8] |> List.map fibProcess is terminated due to StackOverflowException.
Session termination detected.
Press Enter to restart.
Whoops.
Even if I adjust my list comprehension to not include zero:
[1 .. 8] |> List.map fibval it : int list = [1; 2; 3; 5; 8; 13; 21; 34]
We do get something close to the fibonacci sequence but not the exact sequence... You might not think this is important for learning why your intellisense error has occured...
But look carefully at this one now... also notice that I am using 'n' instead of '_':
let rec fib n = match n with | 0 -> 0 | 1 -> 1 | n -> fib(n-1) + fib(n-2);;val fib : int -> int
[0 .. 8] |> List.map fib;;val it : int list = [0; 1; 1; 2; 3; 5; 8; 13; 21]
Now thats the correct sequence.
Unknown : I know its not really the Fibonacci sequence. My tutorial is incorrect. Also why use n instead of _? They both seem to work.thinkhard : Because you are matching on n and not a type variant...
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.