Functional programming · A level · AQA 7517 4.12.2.1, Eduqas A500QS 1.4 · about 25 min
The three higher-order functions, foldl and foldr, and a pipeline over a log of sensor readings.
[1 mark]What does this program print?
cms = [12, 45, 30, 61] print(list(map(lambda cm: cm * 10, filter(lambda cm: cm > 25, cms))))
[1 mark]What does filter do?
[1 mark]What is the value of foldl (-) 10 [1,2,3]?
[1 mark]What is the value of foldr (-) 0 [5,3,1]?
[1 mark]What does this program print?
from functools import reduce log = [(0, 40), (90, 15), (180, 62), (270, 33)] far = reduce(lambda a, b: a if a[1] >= b[1] else b, log) print(far[0])
[1 mark]What is the result of the Haskell expression map (*2) [1,2,3]? Write it as a Haskell list.
Analyse sweep.csv (above) with map, filter and fold. There must be no for or while anywhere in the program (so no comprehensions either), and no min, max or sum: use map, filter and reduce instead.
- parse(line) takes one line of the file, such as "2.4,60,24.5", and returns a tuple (time, heading, cm) with time a float, heading an int and cm a float.
- Read the file, skip the header line, and map parse over the rest.
- Keep only the valid readings, those under 400 cm, and print valid: <how many>.
- Of the valid readings, print the headings of those over 40 cm, in the order they are in the file, as clear: 0 30 ... separated by spaces.
- Fold the valid readings to find the nearest, and print nearest: <cm> cm at <heading>.
- Fold the valid readings to their total, and print mean: <mean cm> rounded to one decimal place.
The robot does not move.
# the two lines every program starts with: the commands, then the robot
from bugbot import *
connect()
from functools import reduce
f = open("sweep.csv", "r")
lines = f.read().splitlines()
f.close()
for line in lines[1:]:
print(line)Plan your program here, then type it in and press Run.
foldr (-) 0 [5,3,1] and foldl (-) 0 [5,3,1] with brackets, work out both, then check the left one with reduce.len, to count how many valid readings are under 20 cm.my_map(f, xs) and my_filter(p, xs) using recursion and no loops.