2013-07-30 1 views
6

Ho lavorato con alcune funzioni di Haskell, alcune le ho capite e altre no.Come funziona scanr? Haskell

Per esempio, se facciamo: scanl (+) 0 [1..3] la mia comprensione è la seguente:

1. the accumulator is 0     acc   = 0 | 
2. (+) applied to acc and first el  acc = 0 + 1 = 1 | 
3. (+) applied to latest acc and snd el acc = 1 + 2 = 3 | 
4. (+) applied to latest acc and third acc = 3 + 3 = 6 V 

Ora, quando facciamo la lista otteniamo [0, 1, 3, 6].

Ma io non riesco a capire come si fa scanr (+) 0 [1..3] mi da: [6,5,3,0] Forse scanr funziona nel seguente modo?

1. the first element in the list is the sum of all other + acc 
2. the second element is the sum from right to left (<-) of the last 2 elements 
3. the third element is the sum of first 2... 

Non vedo se quello è il modello o no.

risposta

6

scanr è a foldr quello che scanl è a foldl. foldr opere da destra:

foldr (+) 0 [1,2,3] = 
    (1 + (2 + (3 + 0))) = 
    (1 + (2 + 3)) = 
    (1 + 5) = 
    6 

e scanr mostra solo i risultati intermedi in sequenza: [6,5,3,0].