简体   繁体   English

Scala:使用左折时类型不匹配

[英]Scala: Type mismatch when using left fold

Playing around with implementation of list function 试玩列表功能的实现

sealed trait List[+A]

case object Nil extends List[Nothing]
case class Cons[+A] (head:A, tail:List[A]) extends List[A]

object List {
  @tailrec
  def foldLeft[A,B] (list: List[A], z:B)(f:(A,B) => B) : B = {
    list match {
      case Nil => z
      case Cons(h,t) => foldLeft(t,f(h,z))(f)
    }
  }

  def reverse[A] (list: List[A]) = {
    foldLeft(list,Nil)(Cons(_,_))
  }
}

getting "Type mismatch, expected (A,Nil.Type) => Nil.Type, actual: (A, Nil.Type) => Cons[A]" from the Cons( , ) in the reverse method. 以相反的方法从Cons( )获取“类型不匹配,预期(A,Nil.Type)=> Nil.Type,实际:(A,Nil.Type)=> Cons [A]”。

What am I doing wrong ? 我究竟做错了什么 ?

This is a very common error when using Nil . 使用Nil时,这是一个非常常见的错误。 Nil extends List[Nothing] so you need to help the compiler a little bit to properly infer the actual type of B : Nil扩展了List[Nothing]因此您需要一点帮助编译器正确推断B的实际类型:

def reverse[A] (list: List[A]) = {
    foldLeft(list,Nil:List[A])(Cons(_,_))
  }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM