Scala-无法从泛型推断类型
我是Scala新手,无法正确使用此代码,任何帮助都将不胜感激!这是我的Scala-无法从泛型推断类型,scala,Scala,我是Scala新手,无法正确使用此代码,任何帮助都将不胜感激!这是我的 sealed trait List[+A] { def foldRight[B](f: (B, A) => B, acc: B): B = { def go(acc: B, list: List[A]): B = list match { case Nil => acc case Cons(x, xs) => go(f(acc, x), xs) } go(
sealed trait List[+A] {
def foldRight[B](f: (B, A) => B, acc: B): B = {
def go(acc: B, list: List[A]): B = list match {
case Nil => acc
case Cons(x, xs) => go(f(acc, x), xs)
}
go(acc, this)
}
}
case object Nil extends List[Nothing]
case class Cons[+A](x: A, xs: List[A]) extends List[A]
val list: List[Int] = Cons(1, Cons(2, Cons(3, Cons(4, Nil))))
val acc: Int = 0
// this one works
println(list.foldRight((x: Int, y: Int) => x + y, acc))
// this one says cannot resolve symbol +
println(list.foldRight((x, y) => x + y, acc))
我不明白为什么它不能推断类型,因为list是list[Int](A),foldRight的第二个参数是Int(B)。有什么想法吗?Scala编译器需要帮助 这里Scala编译器无法为您推断类型,因为
+
可以是字符串串联运算符或数字加法运算符。要消除这种混淆,您必须至少提供输出类型B
asInt
您至少需要告诉B
属于哪种类型,以帮助编译器了解+
是字符串串联还是数字加法
告诉编译器什么是B
(结果类型),或者告诉编译器什么是x
和y
list.foldRight[Int]((x,y)=>x+y,acc)
下面的代码有效
println(list.foldRight[Int]( (x, y) => x + y , acc ) )
Scala REPL
scala> :paste
// Entering paste mode (ctrl-D to finish)
sealed trait List[+A] {
def foldRight[B](f: (B, A) => B, acc: B): B = {
def go(acc: B, list: List[A]): B = list match {
case Nil => acc
case Cons(x, xs) => go(f(acc, x), xs)
}
go(acc, this)
}
}
case object Nil extends List[Nothing]
case class Cons[+A](x: A, xs: List[A]) extends List[A]
val list: List[Int] = Cons(1, Cons(2, Cons(3, Cons(4, Nil))))
val acc: Int = 0
// Exiting paste mode, now interpreting.
defined trait List
defined object Nil
defined class Cons
list: List[Int] = Cons(1,Cons(2,Cons(3,Cons(4,Nil))))
acc: Int = 0
scala> println(list.foldRight[Int]( (x, y) => x + y , acc ) )
10
Scala编译器需要帮助 这里Scala编译器无法为您推断类型,因为
+
可以是字符串串联运算符或数字加法运算符。要消除这种混淆,您必须至少提供输出类型B
asInt
您至少需要告诉B
属于哪种类型,以帮助编译器了解+
是字符串串联还是数字加法
告诉编译器什么是B
(结果类型),或者告诉编译器什么是x
和y
list.foldRight[Int]((x,y)=>x+y,acc)
下面的代码有效
println(list.foldRight[Int]( (x, y) => x + y , acc ) )
Scala REPL
scala> :paste
// Entering paste mode (ctrl-D to finish)
sealed trait List[+A] {
def foldRight[B](f: (B, A) => B, acc: B): B = {
def go(acc: B, list: List[A]): B = list match {
case Nil => acc
case Cons(x, xs) => go(f(acc, x), xs)
}
go(acc, this)
}
}
case object Nil extends List[Nothing]
case class Cons[+A](x: A, xs: List[A]) extends List[A]
val list: List[Int] = Cons(1, Cons(2, Cons(3, Cons(4, Nil))))
val acc: Int = 0
// Exiting paste mode, now interpreting.
defined trait List
defined object Nil
defined class Cons
list: List[Int] = Cons(1,Cons(2,Cons(3,Cons(4,Nil))))
acc: Int = 0
scala> println(list.foldRight[Int]( (x, y) => x + y , acc ) )
10
在scala中使用lambda函数而不显式指定类型的惯用方法是
case
:
println(list.foldRight({ case (x, y) => x + y }, acc))
在scala中使用lambda函数而不显式指定类型的惯用方法是
case
:
println(list.foldRight({ case (x, y) => x + y }, acc))
复制答案的要点是:使用currying让编译器推断正确的类型。复制答案的要点是:使用currying让编译器推断正确的类型。这行不通这行不通