Sort each part of the word-frequency program by whether it can be written as a pure function or must carry mutable state.
Groups: Can be pure · Must carry mutable state
- The dictionary that accumulates counts as words arrive
- Splitting a string into a list of lower-case words
- The running tally updated once per word of the text
- Formatting a finished count table as text for display
- Selecting the ten largest counts from a finished dictionary
Hints
- A pure function computes its answer from its arguments alone and leaves nothing changed behind.
- Anything that accumulates across many inputs has to remember something between them.
Show the answer
Can be pure: Splitting a string into a list of lower-case words, Formatting a finished count table as text for display, Selecting the ten largest counts from a finished dictionary
Must carry mutable state: The dictionary that accumulates counts as words arrive, The running tally updated once per word of the text
Splitting, formatting and selecting all take a finished input and return a finished answer, so they can be pure and trivially tested. Accumulation is inherently stateful, which is why the advice is not to eliminate mutation but to contain it in the one place that genuinely needs it, keeping the rest pure.
Practise Integrated Programming Synthesis
The app has 5 more questions on this lesson, and keeps your place in the course. Computer Science I is free to start.
More questions on Integrated Programming Synthesis
- A word-frequency counter needs to split text, normalise case, count occurrences and report the top results.…
- Order the tasks of building the word-frequency counter so that each one can be tested as soon as it is…
- A word-frequency program is asked to handle a 50 GB file that will not fit in memory. Which part of the…
- Select every edge case the lesson says the word-frequency counter's tests should cover.