为什么 Scala 既提供多个参数列表又提供每个列表多个参数? [英] Why does Scala provide both multiple parameters lists and multiple parameters per list?

查看:24
本文介绍了为什么 Scala 既提供多个参数列表又提供每个列表多个参数?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

多个参数列表,例如def foo(a:Int)(b:Int) = {} 和每个列表的多个参数,例如def foo(a:Int, b:Int) = {} 据我所知在语义上是等价的,而且大多数函数式语言只有一种声明多个参数的方法,例如F#.

Multiple parameters lists, e.g. def foo(a:Int)(b:Int) = {} and multiple parameters per list, e.g. def foo(a:Int, b:Int) = {} are semantically equivalent so far as I can tell, and most functional languages have only one way of declaring multiple parameters, e.g. F#.

我认为支持这两种函数定义风格的唯一原因是允许使用只有一个参数的参数列表进行类似语法的语言扩展.

The only reason I can figure out for supporting both these styles of function definitions is to allow syntax-like language extensions using a parameter list that has only one parameter in it.

def withBufferedWriter(file: File)(block: BufferedWriter => Unit)

现在可以使用语法来调用

can now be called with the syntax-looking

withBufferedWriter(new File("myfile.txt")) { out =>
  out write "whatever"
  ...
}

但是,可以有其他方法来支持使用大括号而无需多个参数列表.

However, there could be other ways of supporting the use of curly braces without having multiple parameter lists.

一个相关的问题:为什么在 Scala 中使用多个参数列表被称为currying"?柯里化通常被定义为一种为了支持部分应用而使 n 元函数成为一元函数的技术.然而,在 Scala 中,可以部分应用一个函数,而无需创建函数的柯里化"(多个参数列表,每个列表一个参数)版本.

A related question: why is the use of multiple parameter lists in Scala called "currying"? Currying is usually defined as a technique for making an n-ary function unary for the sake of supporting partial application. However, in Scala one can partially apply a function without making a "curried" (multiple parameter lists with one param each) version of the function.

推荐答案

它让你能够做到例如:

scala> def foo(as: Int*)(bs: Int*)(cs: Int*) = as.sum * bs.sum * cs.sum
foo: (as: Int*)(bs: Int*)(cs: Int*)Int

scala> foo(1, 2, 3)(4, 5, 6, 7, 9)(10, 11)
res7: Int = 3906

这篇关于为什么 Scala 既提供多个参数列表又提供每个列表多个参数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆