Scala: tupled メソッドを使ってタプルを関数の引数として渡す
タプルを直接関数のパラメータとして受け渡したい場合には、Function2, Function3, ... トレイトの tupled を使うと便利。
1 2 3 4 5 | scala> def f(x : Int, y : Int, z : Int) : Int = x + y + z f : (x : Int, y : Int, z : Int)Int scala> (f _ ).tupled(( 10 , 20 , 30 )) res 0 : Int = 60 |
特に Case Class の組み立てに役立つ。
1 2 3 4 5 | scala> case class C(x : Int, y : Int, z : Int) defined class C scala> Seq(( 1 , 2 , 3 ), ( 4 , 5 , 6 ), ( 7 , 8 , 9 )).map(C.tupled) res 1 : Seq[C] = List(C( 1 , 2 , 3 ), C( 4 , 5 , 6 ), C( 7 , 8 , 9 )) |
同様に、curried メソッドも備わっている。
1 2 | scala> (f _ ).curried( 10 )( 20 )( 30 ) res 2 : Int = 60 |
0 件のコメント:
コメントを投稿