Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why isn't there a scanl' function in the Haskell standard library?

Tags:

haskell

The foldl function comes with a strict analog foldl'. Is there a reason why scanl doesn't need a scanl' alternative or did they simply not include it in the standard library?

like image 465
hugomg Avatar asked Nov 22 '13 01:11

hugomg


2 Answers

There's no need for it. The strictness of foldl' allows it to eliminate thunks immediately as it traverses its input list.

foldl' (+) 0 [1,2,3]           foldl (+)    0                [1,2,3]
foldl' (+) 1 [2,3]             foldl (+)   (0 + 1)           [2,3]
foldl' (+) 3 [3]               foldl (+)  ((0 + 1) + 2)      [3]
foldl' (+) 6 []                foldl (+) (((0 + 1) + 2) + 3) []
6                                        (((0 + 1) + 2) + 3)
                                          ((1 + 2) + 3)
                                           (3 + 3)
                                            6

But when you do scanl it produces a list containing each one of those steps

scanl (+) 0 [1,2,3]
[   0
,   0 + 1
,  (0 + 1) + 2
, ((0 + 1) + 2) + 3
]

And you must traverse the entire list to see the final result which lets you control how the thunks are forced. This pushes the control of evaluation to the consumer of the list.

like image 111
J. Abrahamson Avatar answered Nov 05 '22 01:11

J. Abrahamson


Well, I'm not sure if scanl' isn't needed, but it probably is a much rarer need than foldl', since you typically consume the result of scanl element by element, and hence force it as you go exactly the way foldl' does.

like image 22
Daniel Wagner Avatar answered Nov 05 '22 03:11

Daniel Wagner