News for hackers. Stuff that matters.
Re:Revenge of the Types by joneil on Monday August 25, 2014 @04:51AM (#8221049)
Adding to all the other answers, here is what Haxe can do:

    class Metric {
        static function main() {
            var coinRadius:Millimeters = 12;
            var myHeight:Centimeters = 180;
            var raceLength:Meters = 200;
            var commuteDistance:Kilometers = 23;

            diff( coinRadius, myHeight ); // 1.788 meters
            diff( raceLength, commuteDistance ); // 22800 meters
            sum( commuteDistance, coinRadius ); // 23000.012 meters
        }

        static function diff( a:Meters, b:Meters ) {
            var d = Math.abs( a-b );
            trace( '$d meters' );
        }

        static function sum( a:Meters, b:Meters ) {
            var s = Math.abs( a+b );
            trace( '$s meters' );
        }
    }
And the best part is, at runtime those are all floats. Take a look at the compiled JS code:

    (function () { "use strict";
    var Metric = function() { };
    Metric.main = function() {
            var coinRadius = 12;
            var myHeight = 180;
            var raceLength = 200;
            var commuteDistance = 23;
            Metric.diff(coinRadius / 1000,myHeight / 100);
            Metric.diff(raceLength,commuteDistance * 1000);
            Metric.sum(commuteDistance * 1000,coinRadius / 1000);
    };
    Metric.diff = function(a,b) {
            var d = Math.abs(a - b);
            console.log("" + d + " meters");
    };
    Metric.sum = function(a,b) {
            var s = Math.abs(a + b);
            console.log("" + s + " meters");
    };
    Metric.main();
    })();
The compiler takes care of all the conversions for you. To see the complete compileable example, including my type definitions for each unit, take a look at this gist: https://gist.github.com/jasononeil/b6b1845824f45f5d19df

And the manual on abstract types: http://haxe.org/manual/abstracts

There are no comments on this comment yet.