简体   繁体   中英

F# error: Wrong type expected?

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM