2017-05-26 1 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)) 

Je ne suis pas sûr comment List [A] dans foldLeft est de type B. Quelqu'un peut-il effacer le processus qui se passe dans cette fonction?inverser en utilisant foldLeft dans scala

Répondre

1

Cette implémentation inverse appelle foldLeft avec A comme il est le premier argument de type (foldLeft#A = A) et List[A] comme il est deuxième argument de type (foldLeft#B = List[A]). Voici une version de type annotée qui rend cette très explicite:

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

également Cons (si elle est une Cons de la bibliothèque standard) crée un flux au lieu de la liste. Probablement Vous voulez utiliser :: à la place:

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