2014-11-21 70 views
1

與執行列表功能斯卡拉:在使用類型不匹配左摺疊

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(_,_)) 
    } 
} 

收到「類型不匹配,期望(A,Nil.Type)=> Nil.Type,實際的播放圍:(A,無.Type)=> Cons [A]「(Consumption())。

我在做什麼錯?

回答

6

這是使用Nil時非常常見的錯誤。 Nil延伸List[Nothing]所以你需要幫助編譯器一點點來正確推斷B的實際類型:

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