I'm noobing around with F# trying to create overloads of cos that accepts angles with units.

This is my code:

[<Measure>] type rad
[<Measure>] type deg
let toRad(x:float<deg>) =
    (float x) * 3.14159265 / 180.0
    |> LanguagePrimitives.FloatWithMeasure<rad>
let cos (angle: float<rad>) = cos(float angle)
let cos (angle: float<deg>) = cos(toRad angle) // get duplicate definition of cos here

Compiler complains about duplicate definition of cos on the last row.

有帮助吗?

解决方案

Measure types are erased (see the specification), so you effectively have two definitions of cos(angle: float) which causes the error.

You could create a union type for the two possibilities

type Angle = Degrees of float | Radians of float

or give the functions different names.

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top