News for hackers. Stuff that matters.
Re:The Problem with F# Evangelism by yawaramin on Tuesday August 22, 2017 @08:30PM (#15077526)
Units of measure. So in C# you can do something like this (using floats for convenience):

    class Power {
      public static HoursUsed(
        float totalBillDlrs, float deviceWattage, float rateDlrsPerkWh) {
        return 1000.0 * totalBillDlrs / (deviceWattage * rateDlrsPerkWh);
      }
    }
Then call it like this:

    var totalBillDlrs = 10.95;
    var deviceWattage = 100.0;
    var rateDlrsPerkWh = 0.15;

    Power.HoursUsed(deviceWattage, totalBillDlrs, rateDlrsPerkWh);
But, oops! that was actually supposed to be:

    Power.HoursUsed(totalBillDlrs, deviceWattage, rateDlrsPerkWh);
In F# you can use units of measure to prevent this kind of thing at compile time:

    [<Measure>] type dollar
    [<Measure>] type watt
    [<Measure>] type kilowatt
    [<Measure>] type hour

    module Power =
      let hoursUsed
        (totalBill : float<dollar>)
        (deviceWattage : float<watt>)
        (rate : float<dollar/(kilowatt hour)>) : float<hour> =
        1000.0<watt/kilowatt> * totalBill / (deviceWattage * rate)

    let totalBill = 10.95<dollar>
    let deviceWattage = 100.0<watt>
    let rate = 0.15<dollar/(kilowatt hour)>

    // Compile error
    Power.hoursUsed deviceWattage totalBill rate
And, yes, in C# you can use things like named parameters to reduce the chances of something like this, but you can't eliminate it at compile time, which is what F# does.

There are no comments on this comment yet.