LoginSignup
3
0

More than 5 years have passed since last update.

Scalaのカリー化 自分用まとめ

Last updated at Posted at 2016-09-07

自分用のまとめ

 数値の最大値を求める関数をいくつか書いてみる

/*関数定義*/
val sample = (x:Int)=> {x}
//sample: Int => Int = <function1>  1引数を取りInt型の値を返す関数)を返す関数
/*2値の大きいほうを求める関数*/
val max_ = (x:Int,y:Int)=>{
    if (x>y){x}else{y}
}
//max_: (Int, Int) => Int = <function2> 2引数をとりInt型の値を返す関数
/*10と大きさを比較し大きいほうを返す関数をmax_をもとに作る*/
val max_10 = max_(10)
//エラー発生
Main.scala:25: not enough arguments for method apply: (v1: Int, v2: Int)Int in trait Function2.
Unspecified value parameter v2.
max_(10)
/*カリー化*/
val max_c = max_.curried
//max_c: Int => Int => Int = <function1> -> max_c: Int => (Int => Int = <function1>) //1引数をとり (1引数を取りInt型の値を返す関数)を返す関数を返す関数

/*10と大きさを比較し大きいほうを返す関数をmax_cをもとに作る*/
val max_10 = max_c(10)
//max_10: Int => Int = <function1> 1引数をとりInt型の値を返す関数

/*10と比較して大きいほうを求める*/
max_10(11) /* 11 */
max_10(9)  /*  10 */
max_c(10)(11) /* 11 */
max_c(10)(9)  /*  10 */
//max_10(11)はmax_c(10)(11)ともかける
/*3つの数値の中から一番大きい値を求める*/
val max3_ = (x:Int,y:Int,z:Int)=>{
    max_(z,max_(x,y))
}
/*カリー化*/
val max3_c = max3_.curried

関数の定義と自分の認識

  • max_: (Int, Int) => Int = <function2> 
    • 2引数をとりInt型の値を返す関数
  • max_c: Int => Int => Int = <function1> -> max_c: Int => (Int => Int = <function1>)

    • 1引数をとり(1引数を取りInt型の値を返す関数)を返す関数を返す関数
  • max3_: (Int, Int, Int) => Int =<function3>

    • 3引数を取り  Int型の値を返す関数
  • max3_c: Int => Int => Int => Int = <function1> -> max3_c: Int => {Int => (Int => Int = <function1> )} 

    • 1引数をとり (1引数を取り(1引数を取りInt型の値を返す関数)を返す関数) を返す関数を返す関数

まとめ

カリー化の認識
多変数引数関数(なんらかの型を返す)を1引数関数(関数を返す)に変換するという理解でOK?

3
0
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
3
0