Chapter 22
Pure functions and effects
The same moment always gives the same next moment, and the same picture. In Roc, a function's type guarantees that sameness: the type says whether the function has effects.
An effect is anything beyond working out an answer: reading a key, reading the time, painting a canvas. A function with effects carries two marks, one in its name and one in its type, and the compiler rejects a pure function that calls one:
| Code | Term | What it says |
|---|---|---|
-> |
thin arrow | A pure function. It returns an answer worked out from its arguments alone, so the same arguments always give the same answer. |
=> |
thick arrow | A function with effects. It sits in the type in place of ->. |
! |
! suffix |
Ends the name of every function with effects, such as main!, where a Roc program with effects starts. |
A match branch's => is another use of the same symbol. Every function the ride runs has the thin arrow. The effects live in the platform, under the ride's code. The platform times the frames, reads the keys and paints the picture.
The keys §
The viewer's keys reach the ride as a plain value. For each step, the platform reads the keys and hands the app's step a snapshot of them. The step is pure, so the same model and the same snapshot always give the same next model. The “The platform” chapter shows how the keys reach the step.
So every moment of a ride follows from the road it runs on and the keys the viewer presses, and the ride can make any moment again. The next chapter starts on the first of the four things a moment carries: the clock.