Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

F# error: Wrong type expected?

Tags:

types

casting

f#

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?

like image 664
pooperdooper Avatar asked Feb 18 '16 04:02

pooperdooper


1 Answers

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.

like image 125
Jason Down Avatar answered Nov 18 '22 11:11

Jason Down