2017-05-26 19 views
3
def foldLeft[A, B] (as: List[A], z: B) (f: (B, A) => B) : B = as match { 
    case Nil => z 
    case Cons(x, xs) => foldLeft(xs, f(z, x))(f) 
} 

def reverse[A] (as: List[A]): List[A] = 
    foldLeft(as, List[A]())((h, acc) => Cons(acc, h)) 

我不能肯定列表[A]在foldLeft如何爲B型的人可以清除過程中該功能發生了什麼?扭轉階使用foldLeft

回答

1

這種反向實現主叫foldLeftA因爲它是第一種類型的參數(foldLeft#A = A)和List[A]因爲它是第二類型參數(foldLeft#B = List[A])。這是一種註釋版本,使得這個非常明確的:

def reverse[A] (as: List[A]): List[A] = 
    foldLeft[A, List[A]](as = as: List[A], z = List[A]())(
    (h: List[A], acc: A) => Cons(acc, h): List[A] 
) 
1

而且Cons(如果是從標準庫Cons)創建流,而不是名單。可能你想用::代替:

def reverse[A] (as: List[A]): List[A] = 
    foldLeft(as, List[A]())((acc, h) => h :: acc)