by shigemk2

当面は技術的なことしか書かない

Scalaのカリー化

環境

Mac OS X 10.9.1

Scala version 2.10.3

概要

カリー化とは、複数のパラメータをとる関数を1つのパラメータをとる関数のチェーンに変換すること。

コード

scala> def sum(a:Int, b:Int, c:Int) = a + b + c
sum: (a: Int, b: Int, c: Int)Int

scala> val fObj = sum _
fObj: (Int, Int, Int) => Int = <function3>

scala> fObj(1,2,3)
res0: Int = 6

scala> val fObj2 = sum (_:Int, 2, 3) // 部分適用
fObj2: Int => Int = <function1>

scala> fObj2(1)
res1: Int = 6

scala> def sum(a:Int)(b:Int)(c:Int) = a + b + c // カリー化
sum: (a: Int)(b: Int)(c: Int)Int

scala> def sumCurry(a:Int) = (b:Int) => (c:Int) => a + b + c
sumCurry: (a: Int)Int => (Int => Int)

scala> val fObj1 = sumCurry(1)
fObj1: Int => (Int => Int) = <function1>

scala> val fObj2 = fObj1(2)
fObj2: Int => Int = <function1>

scala> fObj2(3)
res2: Int = 6

scala> def sum(a:Int, b:Int, c:Int) = a + b + c
sum: (a: Int, b: Int, c: Int)Int

scala> val currySum = (sum _).curried
currySum: Int => (Int => (Int => Int)) = <function1>

scala> currySum(1)
res3: Int => (Int => Int) = <function1>

scala> currySum(2)
res4: Int => (Int => Int) = <function1>

scala> currySum(3)
res5: Int => (Int => Int) = <function1>

scala> val curry2 = currySum(2)
curry2: Int => (Int => Int) = <function1>

scala> curry2(3)
res6: Int => Int = <function1>

scala> val curry3 = curry2(3)
curry3: Int => Int = <function1>

scala> curry3(4)
res7: Int = 9

ぶんけん