F# operator overloading for conversion of multiple different units of measure

后端 未结 2 1722
逝去的感伤
逝去的感伤 2021-01-01 22:56

I want to be able to do this:

let duration = 1 + 2 + 3

with the following types and functions (a

2条回答
  •  傲寒
    傲寒 (楼主)
    2021-01-01 23:36

    This isn't possible directly within F#. There isn't a way to have the "auto-conversion" succeed directly without specifying the conversion for the types. You would have to explicitly call your conversion functions (seconds_per_minute, etc).

    However, Phil Trelford demonstrated a mechanism by which you could create runtime classes which do support this, though with slightly different syntax. Using his types, you could write:

    let duration = 1.0 * SI.hours + 2.0 * SI.minutes + 3.0 * SI.seconds
    

提交回复
热议问题