Terminology (5)Terms used in this lesson
Term on the front, definition on the back. Paste with tabs between fields and a new line between cards, or import the download in Anki as Basic.
- Higher-order function
- A function that takes another function as an argument or returns one.
- Callback
- A function passed to another function, which decides when to call it.
- Closure
- A function value together with the variables it uses from where it was made.
- Factory
- A function that builds and returns a new function, usually from its arguments.
- Capture
- How a closure holds an outside variable: by reference to the variable, or by its own copy of the value.
Functions can receive and return behavior
A higher-order function accepts a function, returns one, or does both. Passing a callable gives another operation behavior to invoke later; calling that callable executes its body. Its argument and return types describe how the two functions connect.
A closure combines code with access to values from its surrounding scope. Depending on the language and capture form, it can keep an owned value, a copied value or access to a changing binding. Check both the caller’s invocation pattern and the lifetime of everything the callable retains.
01Accepting behavior
A callback runs when the receiving function calls it
A meet’s scoring configuration chooses the highest entry, publishes bonus rules and normalizes heat marks. A published rule must keep the bonus from its creation time. This meet treats 0 as a no-show and adds a configured 1.5 novice adjustment to marks below 6; those are local reporting rules, not universal scoring rules.
The meet’s adjustment must run for each mark. This reduced +2 rule prints when called, isolating invocation timing from the final heat policy. Predict the callback lines and returned scores.
fn apply_to_each(scores: &[i32], rule: impl Fn(i32) -> i32) -> Vec<i32> {
let mut result = Vec::new();
for &score in scores {
result.push(rule(score));
}
result
}
fn add_bonus(score: i32) -> i32 {
println!("bonus for {score}");
score + 2
}
fn main() {
let result = apply_to_each(&[8, 5], add_bonus);
println!("{} {}", result[0], result[1]);
}
rustc --edition=2024 main.rs -o main && ./main
Use the setup from the first reading for your language. Follow the supplied callback type and the points where each function body is invoked.
02Returning behavior
Creating a rule and invoking it run different bodies
Publishing a setting creates behavior for later use. This reduced +3 factory prints while constructing one rule; follow that rule through two later calls and predict the output.
fn make_scorer(bonus: i32) -> impl Fn(i32) -> i32 {
println!("making +{bonus}");
move |score| score + bonus
}
fn main() {
let plus_three = make_scorer(3);
println!("{} {}", plus_three(8), plus_three(1));
}
03Captured values
A function value may read a variable later, or keep a copy
Published rules may be evaluated after the official changes a bonus setting. This single-rule probe changes bonus to 5 after construction; predict what the callback and the outer variable report.
fn main() {
let mut bonus = 1;
let add_bonus = move |score: i32| score + bonus;
bonus = 5;
println!("{} {}", add_bonus(10), bonus);
}
04What the caller does
Each language’s callers pass, bind and copy functions in their own way
For heat normalization, follow both the function value and the way its caller uses it. The selected program tests that boundary before a converter or counting adjustment is connected to the pipeline. Predict its result.
fn apply(rule: fn(i32) -> i32, score: i32) -> i32 {
rule(score)
}
fn main() {
let bonus = 2;
println!("{}", apply(|score| score + 1, 10));
println!("{}", apply(|score| score + bonus, 10));
}
05Repair the meet’s scoring callbacks
Select the best entry, publish stable rules, then normalize heats
First select the highest entry using the supplied comparison callback, keeping the earlier entry on a tie. Then publish one rule at each bonus setting and evaluate those rules later, after the setting has changed. Finally normalize each heat: read the supported integer and half-point marks, remove no-shows coded as 0, apply this meet’s below-6 adjustment and reconcile the count of adjusted marks across all heats.
The caller chooses when each callback runs and which arguments it receives. The configuration and no-show policy are supplied. Decimal marks, delayed rule evaluation and multiple heats distinguish the intended contract from integer parsing, a shared live setting or a copied adjustment counter.
Repair the meet’s scoring callbacks
Keep the first top entry, retain each rule’s publication setting, then normalize heats and reconcile the adjustment count.
In the frontend An event handler is a function you pass, not a call Optional
The meet’s entry list gives each registered name a remove button. Its handler needs a function that removes that name when invoked by the event system.
"use client";
import { useState } from "react";
export default function Entries() {
const [names, setNames] = useState(["ana", "ben"]);
const remove = (name: string) => setNames((all) => all.filter((n) => n !== name));
return (
<ul>
{names.map((name) => (
<li key={name}>
{name} <button onClick={() => remove(name)}>Delete</button>
</li>
))}
</ul>
);
}
onClick={() => remove(name)} passes a function that calls remove on a click. onClick={remove(name)} calls remove while building the list and supplies its void result instead of a handler. Type checking rejects that handler value; unchecked execution would queue entry-removal state updates during render, before a click.
Sources: React: Responding to events,Svelte: Event attributes.
Sources
Sign in to keep your read marks on every device. Sign in
Was this helpful?