gpt4 book ai didi

scala - 使用多个函数参数列表有什么好处?

转载 作者:行者123 更新时间:2023-12-04 22:32:16 26 4
gpt4 key购买 nike

scala> def a(i:Int)(j:Int) = i * j
a: (i: Int)(j: Int)Int

scala> def b(i:Int, j:Int) = i * j
b: (i: Int, j: Int)Int

这两个定义非常相似,它们(在我看来)做同样的事情。

除了定义一个接收隐式参数或代码块作为参数的函数之外,还有什么理由使用第一种定义样式?

最佳答案

这是我长期以来编制的 list :

1) 类型分辨率 跨多个参数列表

class ResourceManager {
type Resource

def open: Resource = ???
}

class ResourceManagerTest {
// Does not compile: def test1(rm: ResourceManager, r: rm.Resource) = ???

// Compiles: This way the type can be resolved
def test2(rm: ResourceManager)(r: rm.Resource) = ???
}

2) 类型推断 其中较早的参数可以为以后的参数“锁定”类型参数(感谢 Myserious Dan)

  def foo1[A](x: A, f: A => Int) = ???

def foo2[A](x: A)(f: A => Int) = ???

def foo1foo2Demo() {
// This will always demand a type annotation on any anonymous function
// you pass in:
foo1(1, (i: Int) => i * i)

// Does not compile: foo1(1, i => i * i)

// Type not required
foo2(2)(i => i * i)
}

3) 类似语法的语言扩展

object MultipleArgumentListsDemo {
// This style of function definition allows syntax-like language extensions
@tailrec
def myWhile(conditional: => Boolean)(f: => Unit) {
if (conditional) {
f
myWhile(conditional)(f)
}
}

def myWhileDemo() {
var count = 0
myWhile(count < 5) {
count += 1
println(count)
}
}

4) 同时拥有 隐式和非隐式参数 , 因为implicit 是整个参数列表的修饰符:

  def f[A](x: A)(implicit mf: Manifest[A]) {
}

5) 一个参数列表中的参数值可用于计算 默认值 在另一个参数列表中,但不在同一个参数列表中。

  def g(x: Int)(y: Int = x * 2) = {
x + y
}

6) 多个重复参数列表 (“可变参数”)

  def h(as: Int*)(bs: Int*)(cs: Int*) = as.sum * bs.sum * cs.sum

7) 部分申请

  def i() {
val foop = h(1, 2, 3)(4, 5, 6, 7, 9) _
println(foop(Seq(10, 11)))
}

由于我在编译该列表时没有跟踪我的来源:部分或所有示例可能是从其他地方复制的(SO 上的其他问题),所以请记下,我将添加关于哪里的引用它来自。

关于scala - 使用多个函数参数列表有什么好处?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18116303/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com