let distance (x:(float * float)): float =
    sqrt ((fst x * fst x) + (snd x * snd x))
let getClosestPair (pairs:(float * float) list) =
    let mutable closest = (0.0, 0.0)
    if List.isEmpty pairs then
        (infinity, infinity)
    else
        closest <- pairs.[0]
        for i in pairs do
            if (distance i) < (distance closest) then closest <- i
The above function goes through a list of float pairs. Each pair acts like a coordinate on the cartesian plane. The function finds the closest pair to the origin. The for loop at the bottom generates a type error.
"This expression was expected to have type float * float but here has type unit"
How would I fix this error?
In the if block you are returning a float * float tuple, but in the else block you are mutating the closest variable and returning unit. These two blocks must return the same type. 
Change your else block to this:
else
    closest <- pairs.[0]
    for i in pairs do
        if (distance i) < (distance closest) then closest <- i
    closest
That ensures you are returning the final result of the closest variable in the else block, which will in turn ensure you are returning a float * float tuple in both the if and else paths.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With