Practice question · Select all that apply
A function is called twice with identical arguments and returns a different answer the second time. Select every explanation the lesson's ideas allow.
Hints
- A pure function is defined by giving the same output for the same inputs, every time.
- Look for options where something outside the argument list, or the argument itself, carried over between calls.
Show the answer
- A. The function keeps a counter of how many times it has been called
- C. The function reads a global variable that changed between the calls
- E. The function mutated one of its arguments during the first call
Why
Any state that survives between calls can change the answer: a global read, an argument the first call mutated, or an internal counter. Purity rules this out by definition, so a differing answer is proof of impurity, which is exactly why pure functions are so much easier to test.
Practise State, Mutation, and Side Effects
The app has 7 more questions on this lesson, and keeps your place in the course. Computer Science I is free to start.
More questions on State, Mutation, and Side Effects
- A function that writes to a global variable is as easy to test as one that only returns a value, provided…
- Order these events so that every stated outcome is true at the moment it is written.
- A function sorts the list it is given rather than returning a sorted copy. Why is that worth documenting…
- Sort each statement by whether it concerns the identity of an object or merely its value.