这两种方法定义之间的区别

时间:2012-10-13 21:20:38

标签: function scala definition

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

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

每个人的目的是什么?

3 个答案:

答案 0 :(得分:4)

第二个是咖喱,第一个不是。有关您可能选择咖喱方法的讨论,请参阅What's the rationale behind curried functions in Scala?

答案 1 :(得分:3)

sayTwords2允许部分应用该方法。

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

注意你也可以用同样的方式使用第一个功能。

val sayHelloAnd = sayTwords("Hello", _:String)
sayHelloAnd("World!")
sayHelloAnd("Universe!")

答案 2 :(得分: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)