views:

132

answers:

2

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?

+4  A: 

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 fib function. Either give the result a name, or write it to the console (which would have the type unit, i.e. "action with no return value"), or something like that.

Daniel Earwicker
Oh ok, for some reason I thought unit said uint.
Unknown
A: 

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 fib

Process 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 fib

val 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.

thinkhard
I know its not really the Fibonacci sequence. My tutorial is incorrect. Also why use n instead of _? They both seem to work.
Unknown
Because you are matching on n and not a type variant...
thinkhard