Programming Search⌘K

Taskcore

Write a higher-order function

Also called function that takes a function, function that returns a function, function factory, apply a function n times, repeat a function.

Write repeat(f, times), which takes a function and returns a new function that applies it times times, and use it to run the step of the Collatz problem a given number of times.

Task

Write a higher-order function repeat(f, times). It takes a function f of one integer and a count times, and it returns a new function. The new function applies f to its argument times times. So repeat(f, 3)(x) is f(f(f(x))), and repeat(f, 0)(x) is x.

Then use repeat with the step of the Collatz problem: "If the number is even, divide it by two."1 "If the number is odd, triple it and add one."1 The entry function collatz_after(start, times) returns repeat(collatz_step, times)(start). For example, collatz_after(6, 3) is 5, because the steps go from 6 to 3, 10 and 5.

start is from 1 to 10000 and times is from 0 to 1000. With these limits each value on the way fits in a 32-bit signed integer. The case peak-9663 has the largest value, 27114424.

A higher-order function is "a function that does at least one of the following: takes one or more functions as arguments (i.e. a procedural parameter, which is a parameter of a procedure that is itself a procedure), returns a function as its result."2 repeat does both. The function that it returns uses f and times after repeat has returned, so in most languages it is a closure. Higher-order function explains the idea, First-class function describes the values that make it possible, and Closure explains how the returned function keeps f and times.

Solutions

Language The type of f What repeat returns
Python Callable[[int], int] a nested function
JavaScript a function value an arrow function
TypeScript (x: number) => number an arrow function
Java Function<Integer, Integer> a lambda expression
C# Func<int, int> a lambda expression
C int (*)(int), a pointer to a function a struct with the pointer and the count
C++ std::function<int(int)> a lambda expression in a std::function
Go func(int) int a function literal
Rust impl Fn(i32) -> i32 a move closure, as impl Fn(i32) -> i32
Bash the name of a function, as a string no function; repeat applies the function at once
  • Python. The Python FAQ gives two ways to make a higher-order function: "You have two choices: you can use nested scopes or you can use callable objects."3 The solution uses a nested function. collatz_step is passed by its name, with no parentheses. A lambda expression also gives a function value, and the tutorial shows a function that returns one: "The above example uses a lambda expression to return a function."4
  • JavaScript. The returned arrow function keeps f and times. MDN defines the mechanism: "A closure is the combination of a function bundled together (enclosed) with references to its surrounding state (the lexical environment)."5 MDN calls a function that makes new functions a function factory: "In essence, makeAdder is a function factory."5
  • TypeScript. The parameter and the result have a function type: "The simplest way to describe a function is with a function type expression."6 The solution names the type Step = (x: number) => number.
  • Java. A lambda expression has the type of a functional interface. The solution uses Function<Integer, Integer>, which "Represents a function that accepts one argument and produces a result."7 Lambda expressions "treat functionality as method argument, or code as data."8 The returned lambda reads f and times. That is allowed, because "a lambda expression can only access local variables and parameters of the enclosing block that are final or effectively final."8 The two parameters do not change.
  • C#. Func<int, int> "Encapsulates a method that has one parameter and returns a value of the type specified by the TResult parameter."9 A lambda expression converts to it: "Convert a lambda expression that has one parameter and returns a value to a Func<T,TResult> delegate."10
  • C. C can pass a function: "A pointer to function can be used on the left-hand side of the function call operator; this invokes the pointed-to function"11. C cannot make a new function at run time. "There are no nested functions (except where allowed through non-standard compiler extensions): each function definition must appear at file scope, and functions have no access to the local variables from the caller"12. So repeat returns a struct repeated with the pointer and the count, and call_repeated applies it. The struct does the work of a closure by hand.
  • C++. "Class template std::function is a general-purpose polymorphic function wrapper."13 It can hold a function pointer or a lambda. A lambda expression "Constructs a closure (an unnamed function object capable of capturing variables in scope)."14 The returned lambda captures f and times by copy, so it is safe to call after repeat returns.
  • Go. "A function type denotes the set of all functions with the same parameter and result types."15 Repeat takes and returns a func(int) int. "Function literals are closures: they may refer to variables declared in a surrounding function."15
  • Rust. A closure has a type that the program cannot write. "Closures are represented by traits, which means you can’t return closures directly."16 The solution returns impl Fn(i32) -> i32. The closure must own f and times, because they go out of scope when repeat returns: "If you want to force the closure to take ownership of the values it uses in the environment even though the body of the closure doesn’t strictly need ownership, you can use the move keyword before the parameter list."17
  • Bash. A Bash function is not a value. "Shell functions are a way to group commands for later execution using a single name for the group."18 The solution passes that name as a string, and "$f" "$x" calls it, because the shell runs a function in the same way as a simple command18. Bash cannot return a new function, so repeat takes the start value too and prints the result.

A lambda and a named function

repeat takes any function of one integer. Here it gets a lambda expression and the named function collatz_step:

from collections.abc import Callable


def repeat(f: Callable[[int], int], times: int) -> Callable[[int], int]:
    def repeated(x: int) -> int:
        for _ in range(times):
            x = f(x)
        return x

    return repeated


def collatz_step(n: int) -> int:
    return n // 2 if n % 2 == 0 else 3 * n + 1


double_ten_times = repeat(lambda x: x * 2, 10)
print(double_ten_times(1))
print(repeat(collatz_step, 77)(27))
print(repeat(collatz_step, 0)(27))
Output
1024
9232
27

From 27, the Collatz sequence climbs "as high as 9232 before descending to 1."1

Edge cases

The cases are in cases/basic.jsonl and cases/edge.jsonl.

  • zero-times: repeat(f, 0) is the identity function, so the result is the start.
  • start-one: from 1, one step gives 4.
  • cycle and past-one: from 1 the steps go to 4, 2 and 1 again. A start of 16 reaches 1 after 4 steps, and after 10 steps it is at 1 again.
  • peak-27: 77 steps from 27 give 9232, the highest value on that path1.
  • peak-9663: 48 steps from 9663 give 27114424, the largest value for any start up to 10000. It fits in 32 bits.
  • limit: 1000 steps from 10000, the largest start and the largest count.

Pitfalls

The result of a call in place of the function

collatz_step is the function. collatz_step(6) is a call, and its result is the number 3. When repeat gets the number, the error comes only when the returned function runs:

This code runs but gives a wrong answer on purpose.

from collections.abc import Callable


def repeat(f: Callable[[int], int], times: int) -> Callable[[int], int]:
    def repeated(x: int) -> int:
        for _ in range(times):
            x = f(x)
        return x

    return repeated


def collatz_step(n: int) -> int:
    return n // 2 if n % 2 == 0 else 3 * n + 1


three_steps = repeat(collatz_step(6), 3)
try:
    print(three_steps(6))
except TypeError as error:
    print(error)
Output
'int' object is not callable

Pass collatz_step with no parentheses.

Functions made in a loop with var

Each function that a loop makes keeps a reference to its variables, not a copy of their values. "Prior to the introduction of the let keyword, a common problem with closures occurred when you created them inside a loop."5

This code runs but gives a wrong answer on purpose.

const adders = [];
for (var i = 1; i <= 3; i++) {
  adders.push((x) => x + i);
}
console.log(adders.map((add) => add(10)));
Output
[ 14, 14, 14 ]

The three functions share one i, and the loop leaves it at 4. With let i, each pass of the loop has its own i, and the result is [ 11, 12, 13 ]. The same problem is in Python, where the FAQ gives the fix lambda n=x: n**23.

Code

The build runs the native tests of each language in a pinned toolchain.

repeat.pyI0RawGitHub
# SPDX-License-Identifier: MIT
# Part of https://programming.tamnd.com/write-a-higher-order-function/.

from collections.abc import Callable


def repeat(f: Callable[[int], int], times: int) -> Callable[[int], int]:
    """Return a function that applies f to its argument times times."""

    def repeated(x: int) -> int:
        for _ in range(times):
            x = f(x)
        return x

    return repeated


def collatz_step(n: int) -> int:
    """Return n / 2 for an even n and 3n + 1 for an odd n."""
    return n // 2 if n % 2 == 0 else 3 * n + 1


def collatz_after(start: int, times: int) -> int:
    """Return the value after times Collatz steps from start."""
    return repeat(collatz_step, times)(start)
test_repeat.py 39 lines
# SPDX-License-Identifier: MIT
# Part of https://programming.tamnd.com/write-a-higher-order-function/.

import pytest

from repeat import collatz_after, collatz_step, repeat

CASES = {
    "one-step": (6, 1, 3),
    "three-steps": (6, 3, 5),
    "ten-steps": (27, 10, 214),
    "zero-times": (7, 0, 7),
    "start-one": (1, 1, 4),
    "cycle": (1, 3, 1),
    "past-one": (16, 10, 1),
    "peak-27": (27, 77, 9232),
    "peak-9663": (9663, 48, 27114424),
    "limit": (10000, 1000, 2),
}


@pytest.mark.parametrize("name", CASES)
def test_collatz_after(name):
    start, times, want = CASES[name]
    assert collatz_after(start, times) == want


def test_repeat_takes_a_lambda():
    assert repeat(lambda x: x * 2, 10)(1) == 1024


def test_repeat_zero_is_identity():
    assert repeat(collatz_step, 0)(27) == 27


def test_each_call_of_repeat_makes_a_new_function():
    twice = repeat(collatz_step, 2)
    three_times = repeat(collatz_step, 3)
    assert (twice(6), three_times(6)) == (10, 5)
repeat.cppI0RawGitHub
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/write-a-higher-order-function/.

#include "repeat.hpp"

#include <utility>

namespace higher_order {

std::function<int(int)> repeat(std::function<int(int)> f, int times) {
    return [f = std::move(f), times](int x) {
        for (int i = 0; i < times; ++i) {
            x = f(x);
        }
        return x;
    };
}

int collatz_step(int n) {
    return n % 2 == 0 ? n / 2 : 3 * n + 1;
}

int collatz_after(int start, int times) {
    return repeat(collatz_step, times)(start);
}

}  // namespace higher_order
repeat.hpp 22 lines
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/write-a-higher-order-function/.

#ifndef REPEAT_HPP
#define REPEAT_HPP

#include <functional>

namespace higher_order {

// Returns a function that applies f to its argument times times.
std::function<int(int)> repeat(std::function<int(int)> f, int times);

// Returns n / 2 for an even n and 3n + 1 for an odd n.
int collatz_step(int n);

// Returns the value after times Collatz steps from start.
int collatz_after(int start, int times);

}  // namespace higher_order

#endif
test_repeat.cpp 54 lines
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/write-a-higher-order-function/.

#include <cstdio>

#include "repeat.hpp"

namespace {

struct test_case {
    const char* name;
    int start, times, want;
};

const test_case cases[] = {
    {"one-step", 6, 1, 3},
    {"three-steps", 6, 3, 5},
    {"ten-steps", 27, 10, 214},
    {"zero-times", 7, 0, 7},
    {"start-one", 1, 1, 4},
    {"cycle", 1, 3, 1},
    {"past-one", 16, 10, 1},
    {"peak-27", 27, 77, 9232},
    {"peak-9663", 9663, 48, 27114424},
    {"limit", 10000, 1000, 2},
};

}  // namespace

int main() {
    int failures = 0;
    for (const auto& c : cases) {
        const int got = higher_order::collatz_after(c.start, c.times);
        if (got != c.want) {
            std::printf("FAIL %s: got %d, want %d\n", c.name, got, c.want);
            ++failures;
        }
    }
    const int doubled = higher_order::repeat([](int x) { return x * 2; }, 10)(1);
    if (doubled != 1024) {
        std::printf("FAIL repeat with a lambda: got %d, want 1024\n", doubled);
        ++failures;
    }
    const int same = higher_order::repeat(higher_order::collatz_step, 0)(27);
    if (same != 27) {
        std::printf("FAIL repeat zero times: got %d, want 27\n", same);
        ++failures;
    }
    if (failures != 0) {
        return 1;
    }
    std::printf("ok\n");
    return 0;
}
HigherOrder.javaI0RawGitHub
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/write-a-higher-order-function/.

import java.util.function.Function;

/** A function that takes a function and returns a function. */
public final class HigherOrder {
    private HigherOrder() {}

    /** Returns a function that applies f to its argument times times. */
    public static Function<Integer, Integer> repeat(Function<Integer, Integer> f, int times) {
        return x -> {
            int value = x;
            for (int i = 0; i < times; i++) {
                value = f.apply(value);
            }
            return value;
        };
    }

    /** Returns n / 2 for an even n and 3n + 1 for an odd n. */
    public static int collatzStep(int n) {
        return n % 2 == 0 ? n / 2 : 3 * n + 1;
    }

    /** Returns the value after times Collatz steps from start. */
    public static int collatzAfter(int start, int times) {
        return repeat(HigherOrder::collatzStep, times).apply(start);
    }
}
HigherOrderTest.java 43 lines
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/write-a-higher-order-function/.

import static org.junit.jupiter.api.Assertions.assertEquals;

import java.util.stream.Stream;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.params.ParameterizedTest;
import org.junit.jupiter.params.provider.Arguments;
import org.junit.jupiter.params.provider.MethodSource;

class HigherOrderTest {
    static Stream<Arguments> cases() {
        return Stream.of(
                Arguments.of("one-step", 6, 1, 3),
                Arguments.of("three-steps", 6, 3, 5),
                Arguments.of("ten-steps", 27, 10, 214),
                Arguments.of("zero-times", 7, 0, 7),
                Arguments.of("start-one", 1, 1, 4),
                Arguments.of("cycle", 1, 3, 1),
                Arguments.of("past-one", 16, 10, 1),
                Arguments.of("peak-27", 27, 77, 9232),
                Arguments.of("peak-9663", 9663, 48, 27114424),
                Arguments.of("limit", 10000, 1000, 2)
        );
    }

    @ParameterizedTest(name = "{0}")
    @MethodSource("cases")
    void collatzAfter(String name, int start, int times, int want) {
        assertEquals(want, HigherOrder.collatzAfter(start, times));
    }

    @Test
    void repeatTakesALambda() {
        assertEquals(1024, HigherOrder.repeat(x -> x * 2, 10).apply(1));
    }

    @Test
    void repeatZeroTimesIsTheIdentity() {
        assertEquals(27, HigherOrder.repeat(HigherOrder::collatzStep, 0).apply(27));
    }
}
repeat.cI0RawGitHub
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/write-a-higher-order-function/.

#include "repeat.h"

struct repeated repeat(step_fn f, int times) {
    struct repeated r = {f, times};
    return r;
}

int call_repeated(struct repeated r, int x) {
    for (int i = 0; i < r.times; i++) {
        x = r.f(x);
    }
    return x;
}

int collatz_step(int n) {
    return n % 2 == 0 ? n / 2 : 3 * n + 1;
}

int collatz_after(int start, int times) {
    return call_repeated(repeat(collatz_step, times), start);
}
repeat.h 29 lines
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/write-a-higher-order-function/.

#ifndef REPEAT_H
#define REPEAT_H

// A pointer to a function from one int to one int.
typedef int (*step_fn)(int);

// C has no closures, so a repeated function is a struct with the function
// and the count.
struct repeated {
    step_fn f;
    int times;
};

// Returns a value that applies f to its argument times times.
struct repeated repeat(step_fn f, int times);

// Applies r to x.
int call_repeated(struct repeated r, int x);

// Returns n / 2 for an even n and 3n + 1 for an odd n.
int collatz_step(int n);

// Returns the value after times Collatz steps from start.
int collatz_after(int start, int times);

#endif
test_repeat.c 56 lines
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/write-a-higher-order-function/.

#include "repeat.h"

#include <stdio.h>
#include <stdlib.h>

struct test_case {
    const char *name;
    int start, times, want;
};

static const struct test_case cases[] = {
    {"one-step", 6, 1, 3},
    {"three-steps", 6, 3, 5},
    {"ten-steps", 27, 10, 214},
    {"zero-times", 7, 0, 7},
    {"start-one", 1, 1, 4},
    {"cycle", 1, 3, 1},
    {"past-one", 16, 10, 1},
    {"peak-27", 27, 77, 9232},
    {"peak-9663", 9663, 48, 27114424},
    {"limit", 10000, 1000, 2},
};

static int twice(int x) {
    return x * 2;
}

int main(void) {
    int failures = 0;
    for (size_t i = 0; i < sizeof cases / sizeof cases[0]; i++) {
        const struct test_case *c = &cases[i];
        int got = collatz_after(c->start, c->times);
        if (got != c->want) {
            printf("FAIL %s: got %d, want %d\n", c->name, got, c->want);
            failures++;
        }
    }
    int doubled = call_repeated(repeat(twice, 10), 1);
    if (doubled != 1024) {
        printf("FAIL repeat(twice, 10): got %d, want 1024\n", doubled);
        failures++;
    }
    int same = call_repeated(repeat(collatz_step, 0), 27);
    if (same != 27) {
        printf("FAIL repeat(collatz_step, 0): got %d, want 27\n", same);
        failures++;
    }
    if (failures != 0) {
        return EXIT_FAILURE;
    }
    printf("ok\n");
    return EXIT_SUCCESS;
}
HigherOrder.csI0RawGitHub
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/write-a-higher-order-function/.

using System;

/// <summary>A function that takes a function and returns a function.</summary>
public static class HigherOrder
{
    /// <summary>Returns a function that applies f to its argument times times.</summary>
    public static Func<int, int> Repeat(Func<int, int> f, int times)
    {
        return x =>
        {
            int value = x;
            for (int i = 0; i < times; i++)
            {
                value = f(value);
            }
            return value;
        };
    }

    /// <summary>Returns n / 2 for an even n and 3n + 1 for an odd n.</summary>
    public static int CollatzStep(int n)
    {
        return n % 2 == 0 ? n / 2 : 3 * n + 1;
    }

    /// <summary>Returns the value after times Collatz steps from start.</summary>
    public static int CollatzAfter(int start, int times)
    {
        return Repeat(CollatzStep, times)(start);
    }
}
HigherOrderTests.cs 41 lines
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/write-a-higher-order-function/.

using Xunit;

public sealed class HigherOrderTests
{
    public static TheoryData<string, int, int, int> Cases => new()
    {
        { "one-step", 6, 1, 3 },
        { "three-steps", 6, 3, 5 },
        { "ten-steps", 27, 10, 214 },
        { "zero-times", 7, 0, 7 },
        { "start-one", 1, 1, 4 },
        { "cycle", 1, 3, 1 },
        { "past-one", 16, 10, 1 },
        { "peak-27", 27, 77, 9232 },
        { "peak-9663", 9663, 48, 27114424 },
        { "limit", 10000, 1000, 2 },
    };

    [Theory]
    [MemberData(nameof(Cases))]
    public void CollatzAfter(string name, int start, int times, int want)
    {
        Assert.NotNull(name);
        Assert.Equal(want, HigherOrder.CollatzAfter(start, times));
    }

    [Fact]
    public void RepeatTakesALambda()
    {
        Assert.Equal(1024, HigherOrder.Repeat(x => x * 2, 10)(1));
    }

    [Fact]
    public void RepeatZeroTimesIsTheIdentity()
    {
        Assert.Equal(27, HigherOrder.Repeat(HigherOrder.CollatzStep, 0)(27));
    }
}
repeat.jsI0RawGitHub
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/write-a-higher-order-function/.

/** Returns a function that applies f to its argument times times. */
export function repeat(f, times) {
  return (x) => {
    let value = x;
    for (let i = 0; i < times; i++) {
      value = f(value);
    }
    return value;
  };
}

/** Returns n / 2 for an even n and 3n + 1 for an odd n. */
export function collatzStep(n) {
  return n % 2 === 0 ? n / 2 : 3 * n + 1;
}

/** Returns the value after times Collatz steps from start. */
export function collatzAfter(start, times) {
  return repeat(collatzStep, times)(start);
}
repeat.test.js 34 lines
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/write-a-higher-order-function/.

import assert from "node:assert/strict";
import { test } from "node:test";

import { collatzAfter, collatzStep, repeat } from "./repeat.js";

const cases = [
  ["one-step", 6, 1, 3],
  ["three-steps", 6, 3, 5],
  ["ten-steps", 27, 10, 214],
  ["zero-times", 7, 0, 7],
  ["start-one", 1, 1, 4],
  ["cycle", 1, 3, 1],
  ["past-one", 16, 10, 1],
  ["peak-27", 27, 77, 9232],
  ["peak-9663", 9663, 48, 27114424],
  ["limit", 10000, 1000, 2],
];

for (const [name, start, times, want] of cases) {
  test(name, () => {
    assert.equal(collatzAfter(start, times), want);
  });
}

test("repeat takes an arrow function", () => {
  assert.equal(repeat((x) => x * 2, 10)(1), 1024);
});

test("repeat with zero times is the identity", () => {
  assert.equal(repeat(collatzStep, 0)(27), 27);
});
repeat.tsI0RawGitHub
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/write-a-higher-order-function/.

/** A function from one number to one number. */
export type Step = (x: number) => number;

/** Returns a function that applies f to its argument times times. */
export function repeat(f: Step, times: number): Step {
  return (x: number): number => {
    let value = x;
    for (let i = 0; i < times; i++) {
      value = f(value);
    }
    return value;
  };
}

/** Returns n / 2 for an even n and 3n + 1 for an odd n. */
export function collatzStep(n: number): number {
  return n % 2 === 0 ? n / 2 : 3 * n + 1;
}

/** Returns the value after times Collatz steps from start. */
export function collatzAfter(start: number, times: number): number {
  return repeat(collatzStep, times)(start);
}
repeat.test.ts 34 lines
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/write-a-higher-order-function/.

import assert from "node:assert/strict";
import { test } from "node:test";

import { collatzAfter, collatzStep, repeat } from "./repeat.ts";

const cases: [string, number, number, number][] = [
  ["one-step", 6, 1, 3],
  ["three-steps", 6, 3, 5],
  ["ten-steps", 27, 10, 214],
  ["zero-times", 7, 0, 7],
  ["start-one", 1, 1, 4],
  ["cycle", 1, 3, 1],
  ["past-one", 16, 10, 1],
  ["peak-27", 27, 77, 9232],
  ["peak-9663", 9663, 48, 27114424],
  ["limit", 10000, 1000, 2],
];

for (const [name, start, times, want] of cases) {
  test(name, () => {
    assert.equal(collatzAfter(start, times), want);
  });
}

test("repeat takes an arrow function", () => {
  assert.equal(repeat((x: number) => x * 2, 10)(1), 1024);
});

test("repeat with zero times is the identity", () => {
  assert.equal(repeat(collatzStep, 0)(27), 27);
});
repeat.goI0RawGitHub
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/write-a-higher-order-function/.

// Package higherorder has a function that takes a function and returns a function.
package higherorder

// Repeat returns a function that applies f to its argument times times.
func Repeat(f func(int) int, times int) func(int) int {
	return func(x int) int {
		for i := 0; i < times; i++ {
			x = f(x)
		}
		return x
	}
}

// CollatzStep returns n / 2 for an even n and 3n + 1 for an odd n.
func CollatzStep(n int) int {
	if n%2 == 0 {
		return n / 2
	}
	return 3*n + 1
}

// CollatzAfter returns the value after times Collatz steps from start.
func CollatzAfter(start, times int) int {
	return Repeat(CollatzStep, times)(start)
}
repeat_test.go 45 lines
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/write-a-higher-order-function/.

package higherorder

import "testing"

var cases = []struct {
	name               string
	start, times, want int
}{
	{"one-step", 6, 1, 3},
	{"three-steps", 6, 3, 5},
	{"ten-steps", 27, 10, 214},
	{"zero-times", 7, 0, 7},
	{"start-one", 1, 1, 4},
	{"cycle", 1, 3, 1},
	{"past-one", 16, 10, 1},
	{"peak-27", 27, 77, 9232},
	{"peak-9663", 9663, 48, 27114424},
	{"limit", 10000, 1000, 2},
}

func TestCollatzAfter(t *testing.T) {
	for _, c := range cases {
		t.Run(c.name, func(t *testing.T) {
			if got := CollatzAfter(c.start, c.times); got != c.want {
				t.Fatalf("got %d, want %d", got, c.want)
			}
		})
	}
}

func TestRepeatTakesAFunctionLiteral(t *testing.T) {
	double := func(x int) int { return x * 2 }
	if got := Repeat(double, 10)(1); got != 1024 {
		t.Fatalf("got %d, want 1024", got)
	}
}

func TestRepeatZeroTimesIsTheIdentity(t *testing.T) {
	if got := Repeat(CollatzStep, 0)(27); got != 27 {
		t.Fatalf("got %d, want 27", got)
	}
}
repeat.rsI0RawGitHub
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/write-a-higher-order-function/.

/// Returns a function that applies f to its argument times times.
pub fn repeat(f: impl Fn(i32) -> i32, times: i32) -> impl Fn(i32) -> i32 {
    move |x| {
        let mut value = x;
        for _ in 0..times {
            value = f(value);
        }
        value
    }
}

/// Returns n / 2 for an even n and 3n + 1 for an odd n.
pub fn collatz_step(n: i32) -> i32 {
    if n % 2 == 0 { n / 2 } else { 3 * n + 1 }
}

/// Returns the value after times Collatz steps from start.
pub fn collatz_after(start: i32, times: i32) -> i32 {
    repeat(collatz_step, times)(start)
}
tests/repeat_test.rs 34 lines
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/write-a-higher-order-function/.

use algo_write_a_higher_order_function::{collatz_after, collatz_step, repeat};

const CASES: &[(&str, i32, i32, i32)] = &[
    ("one-step", 6, 1, 3),
    ("three-steps", 6, 3, 5),
    ("ten-steps", 27, 10, 214),
    ("zero-times", 7, 0, 7),
    ("start-one", 1, 1, 4),
    ("cycle", 1, 3, 1),
    ("past-one", 16, 10, 1),
    ("peak-27", 27, 77, 9232),
    ("peak-9663", 9663, 48, 27114424),
    ("limit", 10000, 1000, 2),
];

#[test]
fn cases() {
    for &(name, start, times, want) in CASES {
        assert_eq!(collatz_after(start, times), want, "{name}");
    }
}

#[test]
fn repeat_takes_a_closure() {
    assert_eq!(repeat(|x| x * 2, 10)(1), 1024);
}

#[test]
fn repeat_zero_times_is_the_identity() {
    assert_eq!(repeat(collatz_step, 0)(27), 27);
}
repeat.shI0RawGitHub
#!/usr/bin/env bash
# SPDX-License-Identifier: MIT
# Part of https://programming.tamnd.com/write-a-higher-order-function/.

# repeat F TIMES X
# Applies the function named F to X, TIMES times, and prints the result.
# A Bash function is not a value, so repeat takes the name of the function
# and cannot return a new function.
repeat() {
  local f=$1 times=$2 x=$3 i
  for ((i = 0; i < times; i++)); do
    x=$("$f" "$x")
  done
  echo "$x"
}

# collatz_step N
# Prints N / 2 for an even N and 3N + 1 for an odd N.
collatz_step() {
  local n=$1
  if ((n % 2 == 0)); then
    echo $((n / 2))
  else
    echo $((3 * n + 1))
  fi
}

# collatz_after START TIMES
# Prints the value after TIMES Collatz steps from START.
collatz_after() {
  repeat collatz_step "$2" "$1"
}
test_repeat.bats 21 lines
#!/usr/bin/env bats
# SPDX-License-Identifier: MIT
# Part of https://programming.tamnd.com/write-a-higher-order-function/.

setup() {
  source "$BATS_TEST_DIRNAME/repeat.sh"
}

double() { echo $(($1 * 2)); }

@test "one-step" { run collatz_after 6 1; [ "$output" = "3" ]; }
@test "three-steps" { run collatz_after 6 3; [ "$output" = "5" ]; }
@test "ten-steps" { run collatz_after 27 10; [ "$output" = "214" ]; }
@test "zero-times" { run collatz_after 7 0; [ "$output" = "7" ]; }
@test "start-one" { run collatz_after 1 1; [ "$output" = "4" ]; }
@test "cycle" { run collatz_after 1 3; [ "$output" = "1" ]; }
@test "past-one" { run collatz_after 16 10; [ "$output" = "1" ]; }
@test "peak-27" { run collatz_after 27 77; [ "$output" = "9232" ]; }
@test "peak-9663" { run collatz_after 9663 48; [ "$output" = "27114424" ]; }
@test "limit" { run collatz_after 10000 1000; [ "$output" = "2" ]; }
@test "repeat takes another function" { run repeat double 10 1; [ "$output" = "1024" ]; }

References

  1. Collatz conjecture, Wikipedia, Statement of the problem; Examples
  2. Higher-order function, Wikipedia, the introduction
  3. Programming FAQ, Python documentation, How do you make a higher order function in Python?
  4. More Control Flow Tools, The Python Tutorial, 4.9.7 Lambda Expressions
  5. Closures, MDN Web Docs JavaScript Guide, Closure; Creating closures in loops, A common mistake
  6. More on Functions, The TypeScript Handbook, Function Type Expressions
  7. Interface Function, Java SE 25 API, the introduction
  8. Lambda Expressions, The Java Tutorials, the introduction; Accessing Local Variables of the Enclosing Scope
  9. Func<T,TResult> Delegate, .NET API, the introduction
  10. Lambda expressions and anonymous functions, C# language reference, the introduction
  11. Pointer declaration, C reference, cppreference.com, Pointers to functions
  12. Functions, C reference, cppreference.com, the introduction
  13. std::function, C++ reference, cppreference.com, the introduction
  14. Lambda expressions, C++ reference, cppreference.com, the introduction; Lambda capture
  15. The Go Programming Language Specification, Function types; Function literals
  16. Advanced Functions and Closures, The Rust Programming Language, Returning Closures
  17. Closures, The Rust Programming Language, Capturing References or Moving Ownership
  18. Shell Functions, Bash Reference Manual, 3.3 Shell Functions

About this page

The build computes these levels from the evidence in the repository. Each row says what the next level needs. Read what the levels mean.

LadderLevelWhat the next level needs
Human proofH0 no proof
  • add a proof in proofs/ (06.5)
LeanL0 no Lean part
  • name a Lean module in the lean field (07)
Code (bash)I0 not checked yet
  • the tests did not run in this build
Code (c)I0 not checked yet
  • the tests did not run in this build
Code (cpp)I0 not checked yet
  • the tests did not run in this build
Code (csharp)I0 not checked yet
  • the tests did not run in this build
Code (go)I0 not checked yet
  • the tests did not run in this build
Code (java)I0 not checked yet
  • the tests did not run in this build
Code (javascript)I0 not checked yet
  • the tests did not run in this build
Code (python)I0 not checked yet
  • the tests did not run in this build
Code (rust)I0 not checked yet
  • the tests did not run in this build
Code (typescript)I0 not checked yet
  • the tests did not run in this build
VisualV0 none
  • add viz/scene.ts or a figure (10)
WritingW3 standard
  • a history with a source