LoginSignup
4
5

More than 5 years have passed since last update.

部分適用で、関数の持つ引数を減らす

Posted at

Haxeでは引数の持つ関数に対していくつかの引数をあらかじめ指定しておき、引数を減らした関数を生成することが可能です。これには、関数が持つbindという関数を使用します。

Main.hx
class Main {
    static function main(){
        var func1:Int->Void = output.bind( 5 );
        var func2:Int->Void = output.bind( _, 8 );

        func1( 12 ); // output( 5, 12 );と同じ
        func2( 12 ); // output( 12, 8 );と同じ
    }

    // Int->Int->Void型の関数
    static function output( a:Int, b:Int ):Void {
        trace( a, b ); // a, bを出力
    }
}

上記のコードではIntの引数を2つ持つoutput関数の片方の引数を束縛して、Intの引数を1つだけ持つ関数を生成しています。

これを、 部分適用 とか 引数の束縛 とか言います。このような引数の束縛は、関数をオブジェクトとして受け渡しをする際に便利です。

例えば、以下のような場合です。

Main.hx
import haxe.Timer;

class Main {
    static function main(){
        //1秒後に、output( 4, 6 )を実行する。
        Timer.delay( output.bind( 4, 6 ), 1000 );
    }

    static function output( a:Int, b:Int ):Void {
        trace( a, b );
    }
}

Timer.delayの最初の引数はVoid->Void (引数も戻り値も持たない関数)なので、outputの2つの引数を束縛することで、Void->Voidの関数を作り出しています。

4
5
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
5