4
4

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

HaxeのAbstractで、暗黙の型変換でFizzBuzzした話

4
Last updated at Posted at 2014-05-07

HaxeのAbstractで、暗黙の型変換でFizzBuzzした

ぼんやり書いてみた。
思った以上に、さっさと書けた。

HaxeのAbstractを説明しながら解説

abstractのポイント

  • 抽象クラスを定義している訳ではない。

  • Abstractは型を定義している。

  • @:from は任意の型から定義している型への型変換を書く。staticじゃないとダメらしい。

  • @:to は@:fromの逆で、定義している型から任意の型への型変換を書く

FizzBuzzTypeの説明

  • @:fromでInt型からFizzBuzzTypeへの型変換を書く

  • @:toでFizzBuzzTypeからString型への型変換を書く。このとき、FizzBuzzの分岐をさせる。

以上です。

FizzBuzz.hx

abstract FizzBuzzType(Int){
    inline function new(i:Int) this = i;

    @:from public static function fromInt(i:Int) 
        return new FizzBuzzType(i);

    @:to public function toString() : String
        return
        if( this % 15 == 0 ) "FizzBuzz"
            else if( this % 3 == 0 ) "Fizz"
                else if( this % 5 == 0 ) "Buzz"
                    else Std.string( this ); 
}

class FizzBuzz{
    public static function main(){
        for( i in 1...100 ){
            var fizzbuzz : FizzBuzzType = i;
            trace( fizzbuzz );
        }
    }

JSにコンパイル したやつ。

ふつーに、型変換しているところに型変換の関数を埋め込んでいる感じ。

(function () { "use strict";
var _FizzBuzz = {};
_FizzBuzz.FizzBuzzType_Impl_ = function() { };
_FizzBuzz.FizzBuzzType_Impl_._new = function(i) {
	return i;
};
_FizzBuzz.FizzBuzzType_Impl_.fromInt = function(i) {
	return i;
};
_FizzBuzz.FizzBuzzType_Impl_.toString = function(this1) {
	if(this1 % 15 == 0) return "FizzBuzz"; else if(this1 % 3 == 0) return "Fizz"; else if(this1 % 5 == 0) return "Buzz"; else if(this1 == null) return "null"; else return "" + this1;
};
var FizzBuzz = function() { };

FizzBuzz.main = function() {
	var _g = 1;
	while(_g < 100) {
		var i = _g++;
		var fizzbuzz = _FizzBuzz.FizzBuzzType_Impl_.fromInt(i);
		console.log(_FizzBuzz.FizzBuzzType_Impl_.toString(fizzbuzz));
	}
};
})();
4
4
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
4
4

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?