Skip to content

Instantly share code, notes, and snippets.

@nenono
Last active August 29, 2015 14:17
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save nenono/2523c406735b11ee9b46 to your computer and use it in GitHub Desktop.
Save nenono/2523c406735b11ee9b46 to your computer and use it in GitHub Desktop.
Scalaでカリー化
// カリー化など
object Currying {
def add(x: Int, y: Int, z: Int) = x + y + z // 式でコードブロック{ ~ }を置き換え可能
def curryTest = {
// defで定義したメソッドだとカリー化できないので、スペース+アンダースコアをつけて関数オブジェクトを取得します
val addFunc = add _
// add _ と書くのは、 add(_, _, _) と書くのと同じっぽい気がします……
// この辺参考になりそうかも: [_ と _ の違い - kmizuの日記](http://kmizu.hatenablog.com/entry/20120917/1347892258)
val a = addFunc.curried// カリー化します
val a1 = a(1)
val a2 = a1(1)
val a3 = a2(1)
println(s"result: ${a1}, ${a2}, ${a3}") // <function1> <function1> 3
// プレイスホルダーに式(変数など)を入れる文字列生成 s"文字列 ${式}"
// StringContextクラスのメソッド呼び出しに変換されます
// この場合 new StringContext("result: ", ", ", ", ").s(a1, a2, a3) になる
// 詳しくはこの辺りを参考に: [文字列の補間 - Scala Documentation](http://docs.scala-lang.org/ja/overviews/core/string-interpolation.html)
// 毎回束縛しなくてもOK
val a4 = (add _ curried)(1)(1)(1)
println(s"result: ${a4}")
}
def main(args: Array[String]) {
curryTest
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment