how to write a generic compare function in Haxe (haxe3)

感情迁移 提交于 2019-12-04 14:31:39

Two type safe ways to deal with the problem:

1. Macros

class Main {
    macro static public function compare_(a, b)
        return macro @:pos(a.pos) { 
            var a = $a, 
            b = $b; 
            if (a <= b) 
                if (b <= a) 0;
                else -1;
            else 1;
        }  

    static function main() {
        var a = 1,
            b = 2;
        trace(compare_(a,b));
    }
}

2. Abstracts

abstract Comparator<T>({f: T->Int }) {
    public function new(f) 
        this = { f: f };

    public function compare(other:T):Int
        return this.f(other);

    @:from static function fromInt(i:Int)
        return simple(i);

    @:from static function fromFloat(f:Float)
        return simple(f);

    @:from static function fromString(s:String)
        return simple(s);

    @:from static function fromComparable<A>(o:{ function compareTo(other:A):Int; })
        return new Comparator(o.compareTo);

    static function simple<X>(o:X):Comparator<X>
        return new Comparator(Reflect.compare.bind(o));
}

class Main {
    static public function compare_<A>(a:Comparable<A>, b:A)
        return a.compare(b);

    static function main() {
        function comparable(value)
             return { 
                 value: value, 
                 compareTo: function(other) 
                     return Reflect.compare(value, other.value) 
             }          
        trace(compare_(1,2));
        trace(compare_(1.5,2.5));
        trace(compare_('foo','bar'));
        trace(compare_(comparable(1),comparable(2))); 
    }
}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!