gpt4 book ai didi

scala - Scala 中的内联函数歧义

转载 作者:行者123 更新时间:2023-12-03 05:51:16 25 4
gpt4 key购买 nike

当将提升为函数的运算符传递给定义的高阶函数之一时,Scala 允许非常简洁的语法,例如(请忽略它可以简化为 .product() 的事实):

List(1,2,3).fold(1)(_ * _)

对于上面我可以直接传递 _\* _

但是,在定义了我自己的玩具函数 zipWith() 后,我在传递函数时需要非常明确:

implicit class EnrichedList[A](val self: List[A]) extends AnyVal {
def zipWith[B, C](that: List[B])
(implicit zipper: A => B => C): List[C] = {

def zipWithHelper(zipper: A => B => C)
(as: List[A])
(bs: List[B]): List[C] = {
(as, bs) match {
case (_, Nil) => Nil
case (Nil, _) => Nil
case (a :: restOfA, b :: restOfB) =>
zipper(a)(b) :: zipWithHelper(zipper)(restOfA)(restOfB)
}
}

zipWithHelper(zipper)(self)(that)
}
}

这个: List(1, 3, 4).zipWith(List(3, 4, 5))(_ * _) 不起作用,说

Error:(60, 46) missing parameter type for expanded function ((x$1: , x$2) => x$1.$times(x$2)) List(1, 3, 4).zipWith(List(3, 4, 5))(_ * _)

我需要说明函数采用什么类型的参数:

List(1, 3, 4).zipWith(List(3, 4, 5))((x: Int) => (y: Int) => x * y)

为什么编译器不允许我只传递简写版本_ * _

最佳答案

表达式 _ * _ 不是 (x: Int) => (y: Int) => x * y 的简写。它是 (x: Int, y: Int) => x * y 的简写。如果将 zipper 类型更改为 (A, B) => C 而不是 A => B => C,它应该可以工作。 柯里化(Currying)是一件事,它不仅仅是恒等函数的一个花哨的名字。

这里编译:

implicit class EnrichedList[A](val self: List[A]) {
def zipWith[B, C](that: List[B])
(implicit zipper: (A, B) => C): List[C] = {

def zipWithHelper(zipper: (A, B) => C)
(as: List[A])
(bs: List[B]): List[C] = {
(as, bs) match {
case (_, Nil) => Nil
case (Nil, _) => Nil
case (a :: restOfA, b :: restOfB) =>
zipper(a, b) :: zipWithHelper(zipper)(restOfA)(restOfB)
}
}

zipWithHelper(zipper)(self)(that)
}
}

println( List(1, 3, 4).zipWith(List(3, 4, 5))(_ * _) )

和打印

List(3, 12, 20)

关于scala - Scala 中的内联函数歧义,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52795409/

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