3

这两个定义有什么区别?:

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

每个的目的是什么?

4

3 回答 3

4

第二个是咖喱,第一个不是。有关为什么选择 curry 方法的讨论,请参阅Scala 中的 curried 函数背后的基本原理是什么?

于 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. 部分应用程序语法。观察:

    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 中的类型推断是根据参数列表进行的,并且从左到右进行。因此,给定一个案例,一个案例可能比其他案例更容易进行类型推断。观察:

    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 回答