← Fundamentals
Fundamentals

Functions as values and higher-order operations

How can a function accept behavior or return new behavior?

Pass behavior as a value and distinguish creating a function from calling it.

Outcome

Tell passing a function from calling it, predict when a callback and a factory run, say what a function value captures and when it reads it in each language, and repair code whose callbacks get the wrong arguments, the wrong values or a copy of their state.

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.

main.rs
Follow appearance
GitHub Light
GitHub Dark
Rosé Pine
Catppuccin Mocha
VS Code Dark+
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]);
}
What is printed?
Rust · terminal.sh
Follow appearance
GitHub Light
GitHub Dark
Rosé Pine
Catppuccin Mocha
VS Code Dark+
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.

main.rs
Follow appearance
GitHub Light
GitHub Dark
Rosé Pine
Catppuccin Mocha
VS Code Dark+
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));
}
What is printed?

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.

main.rs
Follow appearance
GitHub Light
GitHub Dark
Rosé Pine
Catppuccin Mocha
VS Code Dark+
fn main() {
    let mut bonus = 1;
    let add_bonus = move |score: i32| score + bonus;

    bonus = 5;

    println!("{} {}", add_bonus(10), bonus);
}
What is printed?

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.

main.rs
Follow appearance
GitHub Light
GitHub Dark
Rosé Pine
Catppuccin Mocha
VS Code Dark+
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));
}
What does rustc do?

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.

  1. easy · F-HOF-V4-1 Find the best entry
  2. medium · F-HOF-V4-2 Keep each rule’s bonus
  3. hard · F-HOF-V4-3 Boost every heat
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.

Example.tsx
Follow appearance
GitHub Light
GitHub Dark
Rosé Pine
Catppuccin Mocha
VS Code Dark+
"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

Report a problem in this lesson

For typos, mistakes and things that don’t work. We read every report and fix what’s wrong, but we don’t reply here, so a question won’t get an answer.