2013-07-30 4 views
6

J'ai joué avec certaines fonctions de Haskell, certains que j'ai compris et d'autres non.Comment fonctionne scanr? Haskell

Par exemple, si nous faisons: scanl (+) 0 [1..3] ma compréhension est la suivante:

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 

Maintenant, quand nous faisons la liste nous obtenons [0, 1, 3, 6].

Mais je ne peux pas à comprendre comment fonctionne scanr (+) 0 [1..3] me donne: [6,5,3,0] Peut-être scanr fonctionne de la façon suivante?

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... 

Je ne vois pas si c'est le modèle ou non.

Répondre

6

scanr est à foldr ce scanl est à foldl. foldr œuvres du droit:

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

et scanr montre juste les résultats intermédiaires dans l'ordre: [6,5,3,0].