3

これら2つの定義の違いは何ですか?:

def sayTwords(word1: String, word2: String) = println(word1 + " " + word2)
def sayTwords2(word1: String)(word2: String) = println(word1 + " " + word2)

それぞれの目的は何ですか?

4

3 に答える 3

4

2つ目はカレーですが、1つ目はそうではありません。メソッドをカレーすることを選択する理由については、「Scalaのカレー関数の背後にある理論的根拠は何ですか?」を参照してください。

于 2012-10-13T21:29:32.413 に答える
3

sayTwords2メソッドを部分的に適用できます。

val sayHelloAnd = sayTwords2("Hello")
sayHelloAnd("World!")
sayHaelloAnd("Universe!")

最初の関数も同じように使用できることに注意してください。

val sayHelloAnd = sayTwords("Hello", _:String)
sayHelloAnd("World!")
sayHelloAnd("Universe!")
于 2012-10-13T21:35:01.690 に答える
1
def sayTwords(word1: String, word2: String) = println(word1 + " " + word2)
def sayTwords2(word1: String)(word2: String) = println(word1 + " " + word2)

1つ目は、単一のパラメーターリストを含みます。2番目には、複数のパラメーターリストが含まれています。

それらは以下の点で異なります:

  1. 部分適用構文。観察:

    scala> val f = sayTwords("hello", _: String)
    f: String => Unit = <function1>
    
    scala> f("world")
    hello world
    
    scala> val g = sayTwords2("hello") _
    g: String => Unit = <function1>
    
    scala> g("world")
    hello world
    

    前者には、位置構文であるという利点があります。したがって、任意の位置に引数を部分的に適用できます。

  2. 型推論。Scalaの型推論はパラメーターリストごとに機能し、左から右に進みます。したがって、場合によっては、1つが他よりも優れた型推論を容易にする可能性があります。観察:

    scala> def unfold[A, B](seed: B, f: B => Option[(A, B)]): Seq[A] = {
    |   val s = Seq.newBuilder[A]
    |   var x = seed
    |   breakable {
    |     while (true) {
    |       f(x) match {
    |         case None => break
    |         case Some((r, x0)) => s += r; x = x0
    |       }
    |     }
    |   }
    |   s.result
    | }
    unfold: [A, B](seed: B, f: B => Option[(A, B)])Seq[A]
    
    scala> unfold(11, x => if (x == 0) None else Some((x, x - 1)))
    <console>:18: error: missing parameter type
          unfold(11, x => if (x == 0) None else Some((x, x - 1)))
            ^
    
    scala> unfold(11, (x: Int) => if (x == 0) None else Some((x, x - 1)))
    res7: Seq[Int] = List(11, 10, 9, 8, 7, 6, 5, 4, 3, 2, 1)
    
    scala> def unfold[A, B](seed: B)(f: B => Option[(A, B)]): Seq[A] = {
    |   val s = Seq.newBuilder[A]
    |   var x = seed
    |   breakable {
    |     while (true) {
    |       f(x) match {
    |         case None => break
    |         case Some((r, x0)) => s += r; x = x0
    |       }
    |     }
    |   }
    |   s.result
    | }
    unfold: [A, B](seed: B)(f: B => Option[(A, B)])Seq[A]
    
    scala> unfold(11)(x => if (x == 0) None else Some((x, x - 1)))
    res8: Seq[Int] = List(11, 10, 9, 8, 7, 6, 5, 4, 3, 2, 1)
    
于 2012-10-14T08:14:57.340 に答える