Visual Studio F # error

I am learning F # and I stumbled upon 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 will fix this?

+1


a source to share


2 answers


If you enter this code into the interactive console, you expect it to print out the response. But in your program, you need to write a line of code that does something with the return value of your function fib

. Either provide the result, or write it to the console (which will be of type unit

, i.e. Action with no return value) or something like that.



+4


a source


I thought I might add that you are defining your Fibonacci incorrectly. Take a look at your code here:

let rec fib n =
    match n with
    | 1 -> 1
    | 2 -> 2
    | _ -> fib(n-1) + fib(n-2);;

      

Now map this function above the list:

[0 .. 8] |> List.map fib

      

The process is terminating due to a StackOverflowException.

End of session detected.

Press Enter to restart.

Oops.

Even if I tune my list comprehension to not include null:



[1 .. 8] |> List.map fib

      

val it: int list = [1; 2; 3; five; 8; thirteen; 21; 34]

We get something close to the fibonacci sequence, but not the exact sequence ... You might not think this is important in order to find out why your intellisense error occurred ...

But take a close look at this now ... also note 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; five; 8; thirteen; 21]

This is now the correct sequence.

0


a source







All Articles