简体   繁体   中英

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.

What am I doing wrong ?

This is a very common error when using Nil . Nil extends List[Nothing] so you need to help the compiler a little bit to properly infer the actual type of B :

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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