The functional paradigm
Pure functions and side effects, immutability, higher-order functions (map, filter, reduce), composition, recursion in place of loops and lazy evaluation: reading a program built from functions and predicting what it returns.
- 30 cards
- 4 topics
- Free
The outline, topic by topic
Each topic is weighted the way the exam weighs it.
- Concepts
- Questions
- Sort and link
- Scenarios
A few cards from the deck
Pure function: what is it?
Show the answer
A function whose result depends only on its arguments and which changes nothing outside itself: the same arguments always give the same result.
It can be tested without setting up an environment, called in any order, and its call can be replaced by its value without changing the program.
What value does this JavaScript code return?
```javascript
[1, 2, 3, 4].filter(x => x % 2).map(x => x * 10).reduce((a, b) => a + b)`4060100[10, 30]
Show the answer
40x % 2is 1 for odd numbers:filterkeeps 1 and 3,mapgives 10 and 30,reduceadds them: 40. The even numbers would give 60, and withoutfilterit would be 100.A … function always returns the same result for the same arguments and has no ….
Show the answer
A pure function always returns the same result for the same arguments and has no side effect.
Both conditions are needed: a function that reads a global variable or the time depends on the outside, a function that changes its argument acts on the outside.
Side effect: what is it?
Show the answer
Any change a function makes outside itself besides returning its result: changing an outside variable or an argument, writing a file, printing, sending over the network.
A function with no side effect is not necessarily pure: one that reads the time changes nothing, but no longer returns the same value twice in a row for the same arguments.
A price function reads a global “discount rate” variable. A test passes in the morning and fails in the afternoon with the same arguments, because another module changed the rate in between. What is the solution?
- Freeze the global variable with a lock while the test runs
- Rerun the test several times and keep the majority result
- Copy the rate into a second global variable
- Pass the rate as a parameter so the function depends only on its arguments
Show the answer
Pass the rate as a parameter so the function depends only on its arguments
The cause is that the result depends on outside state that other code may change. Making the rate an argument makes the function pure again: same arguments, same price, stable test.