Programming principles and design · Lesson 32 of 60 · Code lesson, JavaScript or Python · Optional
Functional programming
A pure function always returns the same result for the same inputs and changes nothing outside itself.
A higher-order function takes a function as an argument or returns one, as map and filter do.
Building new values instead of changing old ones makes code easier to follow.
Worked example
In JavaScript, numbers.filter(test) keeps the items that pass, and numbers.map(change) builds a new list of results.
const numbers = [1, 2, 3];
const doubled = numbers.map(n => n * 2);
console.log(doubled.join(" "));Output: 2 4 6
In Python, filter(test, numbers) keeps the items that pass, and map(change, numbers) builds the results.
numbers = [1, 2, 3]
doubled = list(map(lambda n: n * 2, numbers))
print(" ".join(map(str, doubled)))Output: 2 4 6
Your turn
The program prints the square of every number. Change it so it only squares the even numbers, by filtering first and then mapping, and prints those squares.
Your program is checked with these 3 inputs:
Input:
1 2 3 4
Expected output:
4 16
Input:
2 3
Expected output:
4
Input:
6
Expected output:
36
Loading your practice…
Preparing your workspace…