When you remove the call to the fibonacci
function the compiler actually reveals the true error: error FS0071: Type constraint mismatch when applying the default type ''a list' for a type inference variable. The types ''a' and ''a list' cannot be unified. Consider adding further type constraints
This is hard to understand but basically there is something wrong with the implementation. I think the problem is your use of List.append
. It should take two lists but you provide it with an int
and an int list
. You can add one item to the front of a list with the ::
operator:
let rec fibonacci x list =
if List.head list > x then List.tail list
else fibonacci x ((List.head list + (List.head (List.tail list))) :: list)
Here is an equivalent implementation that uses pattern matching to simplify the code:
let rec fibonacci x list =
match list with
| a :: b :: rest ->
if a > x then b :: rest
else fibonacci x (a + b :: list)
Note that the compiler warns that the match cases are incomplete. This function will throw an exception if the list has less than 2 items.
Also note that this doesn't work properly: it doesn't produce the Fibonacci sequence. I will leave it with you to fix that.