List of integers to Float in F#

Viewed 344

I just started working with FSharp and have this homework, hope anyone can help me. I have to write a program that takes a list of integers and returns a float. It should be calculated by continued fraction. So if the int list is [4; 5; 6] The float will be calculated by: 4 + (1 / (5 + 1/6) )

The function has to be recursive. I have written the following:

let rec fractionDecimal (numberlist : int list) : float =
  match numberList with
    |[] -> 0.0
    | x :: y -> x + 1.0 / fractionDecimal y

it doesn't work because (fractionDecimal y) float doesn't match the type int. Do you have any suggestions how to solve the problem or what to do to get my code to work? thanks in advance

1 Answers

The problem is that you're trying to add the value of 1.0 / fractionDecimal tail, a float, to head, an int.

You can remedy this situation with the float function.

let rec fractionDecimal (numberList : int list) : float =
    match numberList with
    | [] -> 0.0
    | head :: tail -> float head + 1.0 / fractionDecimal tail

This Microsoft documentation provides a pretty good description of what's happening here: https://docs.microsoft.com/en-us/dotnet/fsharp/language-reference/compiler-messages/fs0001

Related