The answersDownload the PDF
Worksheet

A13.4 Partial application and composition

Functional programming · A level · AQA 7517 4.12.1.4, Eduqas A500QS 1.4 · about 25 min

BugBotLab
NameClassDate

What this lesson is about

Why every Haskell function takes one argument, partial function application, functools.partial, and composing functions into a sensor pipeline.

Questions 6 marks in all

  1. [1 mark]In Haskell, mult x y = x * y and triple = mult 3. What is triple 7?

  2. [1 mark]add :: Integer -> Integer -> Integer. What is the type of add 4?

    1. AInteger -> Integer
    2. BInteger
    3. CInteger -> Integer -> Integer
    4. D(Integer, Integer) -> Integer
  3. [1 mark]f(x) = x + 2 and g(y) = y³. What is (g ∘ f)(2)?

  4. [1 mark]f(x) = x + 2 and g(y) = y³. What is (f ∘ g)(2)?

  5. [1 mark]f: A → B and g: B → C. What is the type of g ∘ f?

    1. AA → C
    2. BC → A
    3. CB → B
    4. DA → B → C
  6. [1 mark]What does this program print?

    def compose(g, f):
        return lambda x: g(f(x))
    
    double = lambda x: x * 2
    less5 = lambda x: x - 5
    print(compose(double, less5)(10), compose(less5, double)(10))

The task: calibrate by composition

Build a calibration pipeline for the distance sensor from small curried functions: - scale(factor) returns a function of one number cm that gives cm * factor. - offset(amount) returns a function of one number cm that gives cm + amount. - compose(g, f) returns a function of one value x that gives g(f(x)). Using only those three, make pipeline: first offset(-2), then scale(10). Apply it to each reading in RAW = (38.0, 51.5, 20.0) and print the results on one line as mm: 360.0 495.0 180.0. Then compose the same two stages in the wrong order and print its results the same way as wrong order: <three numbers>. Round each result 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()

RAW = (38.0, 51.5, 20.0)

def pipeline(cm):
    return cm * 10 - 2

print("mm:", pipeline(RAW[0]))

Plan your program here, then type it in and press Run.

QR code
Do it on the robot
www.bugbotlab.com/learn/a13-4-partial-application-and-composition/
The simulator checks it and tells you when it passes. Nothing to install, no account.

Challenges

  1. partial(clamp, 0, 60) fixes low and high. Can partial fix only high? Try partial(clamp, high=60) and explain what happens.
  2. Write compose_all(functions) that composes a whole list of stages, applying the first in the list first.
  3. Give the types of scale, scale(10) and scale(10)(3.5) in Haskell-style notation.