Introduction To Haskell
Scanning

Introduction

There are two functions scanl and scanr which work just like folding except they make a list of the intermediate steps. These functions are useful for seeing what happens during a fold.

Explaining the steps of a left or right fold is a good pick for an exam question. Scanning instead of folding might help reveal what is happening in more complex folds.

Examples

Here are the fold examples scanned instead of folded.

WinGHCI

Here's an example using max.

WinGHCI

If scanning is being used to make a new list with values depending on previous ones, you might want to drop your starting value.

WinGHCI

The scan functions are very useful for making certain types of list. Consider the triangular number sequence that we produced with a map function. Look at how neatly we can express it using the scan function,

WinGHCI