gpt4 book ai didi

Scala高阶函数混淆

转载 作者:行者123 更新时间:2023-12-05 00:47:44 26 4
gpt4 key购买 nike

在 Scala 中有高阶函数,根据我的理解,要么是返回函数的函数,要么是接受函数的函数。

例如,这是将函数从 Int 转换为 Int 的高阶函数:

def highOrderFunc(f: Int => Int) = {
???
}

为什么当我用 List(1,2,3) 调用 highOrderFunc 时它编译?从这个签名我虽然我需要传递一个函数……我在这里很困惑,有人可以解释一下吗?

最佳答案

List[A]扩展 Seq[A]它也扩展了 PartialFunction[Int, A] :

trait Seq[+A] extends PartialFunction[Int, A]
with Iterable[A]
with GenSeq[A]
with GenericTraversableTemplate[A, Seq]
with SeqLike[A, Seq[A]]

PartialFunction[Int, A]扩展 Function1[A, B](A => B) .在你的情况下 AInt , 所以 Int => IntPartialFunction[Int, Int] 的父级这是 Seq[Int] 的父级这是 List[Int] 的父级.

这就是为什么您可以通过 List[Int]Function1[Int, Int]Int => Int

关于Scala高阶函数混淆,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51139385/

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