Upgrade to Pro — share decks privately, control downloads, hide ads and more …

Scalaで関数

Sponsored · SiteGround - Reliable hosting with speed, security, and support you can count on.

 Scalaで関数

Avatar for Tomohiko Himura

Tomohiko Himura

May 28, 2016
Tweet

More Decks by Tomohiko Himura

Other Decks in Programming

Transcript

  1. repl> def add(x: Int, y: Int) = x + y

    repl> :type add <console>:13: error: missing argument list for method add Unapplied methods are only converted to functions when a function type is expected. You can make this conversion explicit by writing `add _` or `add(_,_)` instead of `add`.
  2. repl> def add(x: Int, y: Int) = x + y

    repl> :type add <console>:13: error: missing argument list for method add Unapplied methods are only converted to functions when a function type is expected. You can make this conversion explicit by writing `add _` or `add(_,_)` instead of `add`. ϝιου͸ؔ਺ʹม׵͠ͳ͍ͱ UZQF͸࢖͑ͳ͍Έ͍ͨ
  3. repl> val args = (1, 2) repl> (add _)(args) error:

    not enough arguments for method apply: (v1: Int, v2: Int)Int in trait Function2. Unspecified value parameter v2.
  4. repl> val args = (1, 2) repl> (add _)(args) error:

    not enough arguments for method apply: (v1: Int, v2: Int)Int in trait Function2. Unspecified value parameter v2. ̎ͭΊͷҾ਺͕ͳ͍ͬͯ͞
  5. repl> (add _)(1)(2) error: not enough arguments for method apply:

    (v1: Int, v2: Int)Int in trait Function2. Unspecified value parameter v2.
  6. repl> (add _)(1)(2) error: not enough arguments for method apply:

    (v1: Int, v2: Int)Int in trait Function2. Unspecified value parameter v2. ΍ͬͺΓ࢖͑ͳ͍ʜ
  7. repl> val basic = add _ repl> val tupled =

    basic.tupled repl> val curried = basic.curried repl> basic(1, 2) // 3 repl> basic((1, 2)) // compile error repl> tupled(1, 2) // 3 repl> tupled((1, 2)) // 3 real> tupled(1 -> 2) // 3 repl> curried(1)(2) // 3
  8. ܕ ͬ͘͟Γ ϕʔγοΫ *OU *OU *OU 'VODUJPO<*OU *OU *OU> ̎ͭͷҾ਺Λड͚औΓ


    Ұͭ஋Λฦؔ͢਺ λϓϧԽ *OU *OU *OU 'VODUJPO< *OU *OU *OU> ͭͷҾ਺ λϓϧ Λड͚औΓ ̍ͭ஋Λฦؔ͢਺ ΧϦʔԽ *OU *OU*OU ̍ͭͷҾ਺Λड͚औΓ
 ҰͭҾ਺Λड͚औΔؔ਺Λฦؔ͢਺
  9. UVQMFE CBTJD DVSSJFE BEEϝιου add _ def add(x: Int, y:

    Int): Int = basic(x, y) def add(x: Int, y: Int): Int = x + y BEE5VQMFEϝιου def addTupled(x: (Int, Int)): Int = x._1 + x._2 basic.tupled Function.untupled(tupled) Function.uncurried(curried) basic.curried (x: Int, y: Int) => x + y BEE$VSSZϝιου def addCurry(x: Int)(y: Int): Int = x + y ((x: (Int, Int)) => x._1 + x._1)((1 , 2)) (x: Int) => (y: Int) => x + y def addTupled(x: (Int, Int)):Int = tupled(x) addTupled _ def addCurry(x: Int)(y: Int) = curried(x)(y) addCurry _
  10. UVQMFE DVSSJFE curried = curry tupled tupled = uncurry curried

    tupled :: (Int, Int) -> Int tupled (x, y) = x + y curried :: Int -> Int -> Int curried x y = x +y
  11. 42