Programming Search⌘K

Taskintro

Define a function

Also called function definition, declare a function, write a function, def, func, fn.

Define a function clamp(value, low, high) that has three parameters and one result, and call it. The result is value limited to the range from low to high.

Task

Define a function clamp(value, low, high) and call it. The function returns value limited to the range from low to high:

  • low when value is less than low,
  • high when value is more than high,
  • value in all other cases.

For example, clamp(42, 0, 10) is 10, clamp(-3, 0, 10) is 0 and clamp(5, 1, 10) is 5. The three parameters and the result are 32-bit signed integers, and low is not more than high.

A function definition gives a name to a block of code and lists its parameters. In a language with static types, it also gives the type of each parameter and the type of the result. The tests call the function with arguments and compare the result. Function explains what a function is, Function signature describes the first line of the definition, and Return value describes the result.

Solutions

Language The definition The call
Python def clamp(value, low, high): clamp(42, 0, 10)
JavaScript function clamp(value, low, high) clamp(42, 0, 10)
TypeScript function clamp(value: number, low: number, high: number): number clamp(42, 0, 10)
Java public static int clamp(int value, int low, int high) in the class Limits Limits.clamp(42, 0, 10)
C# public static int Clamp(int value, int low, int high) in the class Limits Limits.Clamp(42, 0, 10)
C int clamp(int value, int low, int high), declared in clamp.h clamp(42, 0, 10)
C++ int clamp(int value, int low, int high) in the namespace limits limits::clamp(42, 0, 10)
Go func Clamp(value, low, high int32) int32 Clamp(42, 0, 10)
Rust pub fn clamp(value: i32, low: i32, high: i32) -> i32 clamp(42, 0, 10)
Bash clamp() { ... }, which prints the result $(clamp 42 0 10)
  • Python. "The keyword def introduces a function definition. It must be followed by the function name and the parenthesized list of formal parameters. The statements that form the body of the function start at the next line, and must be indented."1 "The return statement returns with a value from a function."1 The solution adds type hints to the parameters and the result. "The Python runtime does not enforce function and variable type annotations."2
  • JavaScript. "The function declaration creates a binding of a new function to a given name."3
  • TypeScript. "When you declare a function, you can add type annotations after each parameter to declare what types of parameters the function accepts."4 "Return type annotations appear after the parameter list"4. The return type is optional: "Much like variable type annotations, you usually don’t need a return type annotation because TypeScript will infer the function’s return type based on its return statements."4 The solution writes it.
  • Java. The solution defines clamp as a method of the class Limits. "The only required elements of a method declaration are the method's return type, name, a pair of parentheses, (), and a body between braces, {}."5 The method is static. Static methods "should be invoked with the class name, without the need for creating an instance of the class"6.
  • C#. "Methods are declared in a class, struct, or interface by specifying the access level such as public or private, optional modifiers such as abstract or sealed, the return value, the name of the method, and any method parameters."7 Clamp is a method of the static class Limits. "A static class is basically the same as a non-static class, but there's one difference: a static class can't be instantiated."8 The caller uses the class name.
  • C. "A function is a C language construct that associates a compound statement (the function body) with an identifier (the function name)."9 "A function is introduced by a function declaration or a function definition."9 The header clamp.h has the declaration, so the test file can call the function. clamp.c has the definition.
  • C++. The definition looks like the C one. "A non-member function definition may appear at namespace scope only"10, and the solution puts it in the namespace limits.
  • Go. "A function declaration binds an identifier, the function name, to a function."11 The type comes after the names, and one type can follow several names, as in the example func(a, b int, z float32) (bool) in the specification11. The name Clamp starts with a capital letter, because an identifier is exported only if "the first character of the identifier's name is a Unicode uppercase letter"11.
  • Rust. "In function signatures, you must declare the type of each parameter."12 For the result, "We don’t name return values, but we must declare their type after an arrow (->)."12 The body has no return: "In Rust, the return value of the function is synonymous with the value of the final expression in the block of the body of a function."12 Here that expression is the if.
  • Bash. A Bash function has no parameter list: "fname () compound-command [ redirections ]"13. "When a function is executed, the arguments to the function become the positional parameters during its execution"13, so the solution reads $1, $2 and $3. The return builtin can "return the value n to its caller"14, but that value is an exit status, and "Exit statuses fall between 0 and 255"15. So clamp prints its result, and the caller reads the output with $( ).

A call with named arguments

Python can also pass the arguments by name. The order of the names does not matter:

def clamp(value: int, low: int, high: int) -> int:
    if value < low:
        return low
    if value > high:
        return high
    return value


print(clamp(42, 0, 10))
print(clamp(high=10, low=0, value=-3))
Output
10
0

Edge cases

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

  • at-low and at-high: a value that is equal to a limit is in the range, so the function returns the value.
  • equal-bounds: when low and high are equal, every value gives that one number.
  • negative-range: the range from -20 to -10 has only negative numbers. The value -50 is below it, so the result is -20.
  • zero: 0 is inside the range from -5 to 5.
  • int-max, int-min and full-range: the largest and the smallest 32-bit integers. The solutions only compare numbers and do no arithmetic, so no value can overflow.

Pitfalls

A missing return in Python

A Python function that ends without a return returns None. "Falling off the end of a function also returns None."1

This code runs but gives a wrong answer on purpose.

def clamp(value, low, high):
    if value < low:
        return low
    if value > high:
        return high


print(clamp(42, 0, 10))
print(clamp(5, 1, 10))
Output
10
None

Add return value as the last line.

A missing argument in JavaScript

JavaScript does not check the number of arguments. "In JavaScript, function parameters default to undefined."16

This code runs but gives a wrong answer on purpose.

function clamp(value, low, high) {
  if (value < low) {
    return low;
  }
  if (value > high) {
    return high;
  }
  return value;
}

console.log(clamp(42, 0));
Output
42

high is undefined, the comparison 42 > undefined is false, and the function returns 42. TypeScript requires the argument unless the definition says that it is optional: "We can model this in TypeScript by marking the parameter as optional with ?"17.

The return status in Bash

A Bash function that puts its result in the return status loses every value above 25515:

This code runs but gives a wrong answer on purpose.

square() {
  return $(( $1 * $1 ))
}

square 20
echo $?
Output
144

400 does not fit, and the caller gets 144. Print the result with echo, and read it with $(square 20).

Code

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

clamp.pyI0RawGitHub
# SPDX-License-Identifier: MIT
# Part of https://programming.tamnd.com/define-a-function/.


def clamp(value: int, low: int, high: int) -> int:
    """Return value limited to the range from low to high."""
    if value < low:
        return low
    if value > high:
        return high
    return value
test_clamp.py 30 lines
# SPDX-License-Identifier: MIT
# Part of https://programming.tamnd.com/define-a-function/.

import pytest

from clamp import clamp

CASES = {
    "inside": (5, 1, 10, 5),
    "below": (-3, 0, 10, 0),
    "above": (42, 0, 10, 10),
    "at-low": (0, 0, 10, 0),
    "at-high": (10, 0, 10, 10),
    "equal-bounds": (7, 3, 3, 3),
    "negative-range": (-50, -20, -10, -20),
    "zero": (0, -5, 5, 0),
    "int-max": (2147483647, -100, 100, 100),
    "int-min": (-2147483648, -100, 100, -100),
    "full-range": (-2147483648, -2147483648, 2147483647, -2147483648),
}


@pytest.mark.parametrize("name", CASES)
def test_clamp(name):
    value, low, high, want = CASES[name]
    assert clamp(value, low, high) == want


def test_keyword_arguments():
    assert clamp(value=15, low=0, high=10) == 10
clamp.cppI0RawGitHub
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/define-a-function/.

#include "clamp.hpp"

namespace limits {

int clamp(int value, int low, int high) {
    if (value < low) {
        return low;
    }
    if (value > high) {
        return high;
    }
    return value;
}

}  // namespace limits
clamp.hpp 15 lines
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/define-a-function/.

#ifndef CLAMP_HPP
#define CLAMP_HPP

// Returns value limited to the range from low to high. The name is in a
// namespace of its own, apart from std::clamp.
namespace limits {

int clamp(int value, int low, int high);

}  // namespace limits

#endif
test_clamp.cpp 46 lines
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/define-a-function/.

#include <climits>
#include <cstdio>

#include "clamp.hpp"

namespace {

struct test_case {
    const char* name;
    int value, low, high, want;
};

const test_case cases[] = {
    {"inside", 5, 1, 10, 5},
    {"below", -3, 0, 10, 0},
    {"above", 42, 0, 10, 10},
    {"at-low", 0, 0, 10, 0},
    {"at-high", 10, 0, 10, 10},
    {"equal-bounds", 7, 3, 3, 3},
    {"negative-range", -50, -20, -10, -20},
    {"zero", 0, -5, 5, 0},
    {"int-max", INT_MAX, -100, 100, 100},
    {"int-min", INT_MIN, -100, 100, -100},
    {"full-range", INT_MIN, INT_MIN, INT_MAX, INT_MIN},
};

}  // namespace

int main() {
    int failures = 0;
    for (const auto& c : cases) {
        const int got = limits::clamp(c.value, c.low, c.high);
        if (got != c.want) {
            std::printf("FAIL %s: got %d, want %d\n", c.name, got, c.want);
            ++failures;
        }
    }
    if (failures != 0) {
        return 1;
    }
    std::printf("ok\n");
    return 0;
}
Limits.javaI0RawGitHub
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/define-a-function/.

/** Functions that keep a number in a range. */
public final class Limits {
    private Limits() {}

    /** Returns value limited to the range from low to high. */
    public static int clamp(int value, int low, int high) {
        if (value < low) {
            return low;
        }
        if (value > high) {
            return high;
        }
        return value;
    }
}
LimitsTest.java 33 lines
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/define-a-function/.

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

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

class LimitsTest {
    static Stream<Arguments> cases() {
        return Stream.of(
                Arguments.of("inside", 5, 1, 10, 5),
                Arguments.of("below", -3, 0, 10, 0),
                Arguments.of("above", 42, 0, 10, 10),
                Arguments.of("at-low", 0, 0, 10, 0),
                Arguments.of("at-high", 10, 0, 10, 10),
                Arguments.of("equal-bounds", 7, 3, 3, 3),
                Arguments.of("negative-range", -50, -20, -10, -20),
                Arguments.of("zero", 0, -5, 5, 0),
                Arguments.of("int-max", 2147483647, -100, 100, 100),
                Arguments.of("int-min", -2147483648, -100, 100, -100),
                Arguments.of("full-range", -2147483648, -2147483648, 2147483647, -2147483648)
        );
    }

    @ParameterizedTest(name = "{0}")
    @MethodSource("cases")
    void clamp(String name, int value, int low, int high, int want) {
        assertEquals(want, Limits.clamp(value, low, high));
    }
}
clamp.cI0RawGitHub
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/define-a-function/.

#include "clamp.h"

int clamp(int value, int low, int high) {
    if (value < low) {
        return low;
    }
    if (value > high) {
        return high;
    }
    return value;
}
clamp.h 10 lines
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/define-a-function/.

#ifndef CLAMP_H
#define CLAMP_H

// Returns value limited to the range from low to high.
int clamp(int value, int low, int high);

#endif
test_clamp.c 44 lines
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/define-a-function/.

#include "clamp.h"

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

struct test_case {
    const char *name;
    int value, low, high, want;
};

static const struct test_case cases[] = {
    {"inside", 5, 1, 10, 5},
    {"below", -3, 0, 10, 0},
    {"above", 42, 0, 10, 10},
    {"at-low", 0, 0, 10, 0},
    {"at-high", 10, 0, 10, 10},
    {"equal-bounds", 7, 3, 3, 3},
    {"negative-range", -50, -20, -10, -20},
    {"zero", 0, -5, 5, 0},
    {"int-max", INT_MAX, -100, 100, 100},
    {"int-min", INT_MIN, -100, 100, -100},
    {"full-range", INT_MIN, INT_MIN, INT_MAX, INT_MIN},
};

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 = clamp(c->value, c->low, c->high);
        if (got != c->want) {
            printf("FAIL %s: got %d, want %d\n", c->name, got, c->want);
            failures++;
        }
    }
    if (failures != 0) {
        return EXIT_FAILURE;
    }
    printf("ok\n");
    return EXIT_SUCCESS;
}
Limits.csI0RawGitHub
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/define-a-function/.

/// <summary>Functions that keep a number in a range.</summary>
public static class Limits
{
    /// <summary>Returns value limited to the range from low to high.</summary>
    public static int Clamp(int value, int low, int high)
    {
        if (value < low)
        {
            return low;
        }
        if (value > high)
        {
            return high;
        }
        return value;
    }
}
LimitsTests.cs 30 lines
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/define-a-function/.

using Xunit;

public sealed class LimitsTests
{
    public static TheoryData<string, int, int, int, int> Cases => new()
    {
        { "inside", 5, 1, 10, 5 },
        { "below", -3, 0, 10, 0 },
        { "above", 42, 0, 10, 10 },
        { "at-low", 0, 0, 10, 0 },
        { "at-high", 10, 0, 10, 10 },
        { "equal-bounds", 7, 3, 3, 3 },
        { "negative-range", -50, -20, -10, -20 },
        { "zero", 0, -5, 5, 0 },
        { "int-max", 2147483647, -100, 100, 100 },
        { "int-min", -2147483648, -100, 100, -100 },
        { "full-range", -2147483648, -2147483648, 2147483647, -2147483648 },
    };

    [Theory]
    [MemberData(nameof(Cases))]
    public void Clamp(string name, int value, int low, int high, int want)
    {
        Assert.NotNull(name);
        Assert.Equal(want, Limits.Clamp(value, low, high));
    }
}
clamp.jsI0RawGitHub
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/define-a-function/.

/** Returns value limited to the range from low to high. */
export function clamp(value, low, high) {
  if (value < low) {
    return low;
  }
  if (value > high) {
    return high;
  }
  return value;
}
clamp.test.js 27 lines
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/define-a-function/.

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

import { clamp } from "./clamp.js";

const cases = [
  ["inside", 5, 1, 10, 5],
  ["below", -3, 0, 10, 0],
  ["above", 42, 0, 10, 10],
  ["at-low", 0, 0, 10, 0],
  ["at-high", 10, 0, 10, 10],
  ["equal-bounds", 7, 3, 3, 3],
  ["negative-range", -50, -20, -10, -20],
  ["zero", 0, -5, 5, 0],
  ["int-max", 2147483647, -100, 100, 100],
  ["int-min", -2147483648, -100, 100, -100],
  ["full-range", -2147483648, -2147483648, 2147483647, -2147483648],
];

for (const [name, value, low, high, want] of cases) {
  test(name, () => {
    assert.equal(clamp(value, low, high), want);
  });
}
clamp.tsI0RawGitHub
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/define-a-function/.

/** Returns value limited to the range from low to high. */
export function clamp(value: number, low: number, high: number): number {
  if (value < low) {
    return low;
  }
  if (value > high) {
    return high;
  }
  return value;
}
clamp.test.ts 27 lines
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/define-a-function/.

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

import { clamp } from "./clamp.ts";

const cases: [string, number, number, number, number][] = [
  ["inside", 5, 1, 10, 5],
  ["below", -3, 0, 10, 0],
  ["above", 42, 0, 10, 10],
  ["at-low", 0, 0, 10, 0],
  ["at-high", 10, 0, 10, 10],
  ["equal-bounds", 7, 3, 3, 3],
  ["negative-range", -50, -20, -10, -20],
  ["zero", 0, -5, 5, 0],
  ["int-max", 2147483647, -100, 100, 100],
  ["int-min", -2147483648, -100, 100, -100],
  ["full-range", -2147483648, -2147483648, 2147483647, -2147483648],
];

for (const [name, value, low, high, want] of cases) {
  test(name, () => {
    assert.equal(clamp(value, low, high), want);
  });
}
clamp.goI0RawGitHub
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/define-a-function/.

// Package limits keeps numbers in a range.
package limits

// Clamp returns value limited to the range from low to high.
func Clamp(value, low, high int32) int32 {
	if value < low {
		return low
	}
	if value > high {
		return high
	}
	return value
}
clamp_test.go 36 lines
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/define-a-function/.

package limits

import (
	"math"
	"testing"
)

var cases = []struct {
	name                   string
	value, low, high, want int32
}{
	{"inside", 5, 1, 10, 5},
	{"below", -3, 0, 10, 0},
	{"above", 42, 0, 10, 10},
	{"at-low", 0, 0, 10, 0},
	{"at-high", 10, 0, 10, 10},
	{"equal-bounds", 7, 3, 3, 3},
	{"negative-range", -50, -20, -10, -20},
	{"zero", 0, -5, 5, 0},
	{"int-max", math.MaxInt32, -100, 100, 100},
	{"int-min", math.MinInt32, -100, 100, -100},
	{"full-range", math.MinInt32, math.MinInt32, math.MaxInt32, math.MinInt32},
}

func TestClamp(t *testing.T) {
	for _, c := range cases {
		t.Run(c.name, func(t *testing.T) {
			if got := Clamp(c.value, c.low, c.high); got != c.want {
				t.Fatalf("got %d, want %d", got, c.want)
			}
		})
	}
}
clamp.rsI0RawGitHub
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/define-a-function/.

/// Returns value limited to the range from low to high.
pub fn clamp(value: i32, low: i32, high: i32) -> i32 {
    if value < low {
        low
    } else if value > high {
        high
    } else {
        value
    }
}
tests/clamp_test.rs 32 lines
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/define-a-function/.

use algo_define_a_function::clamp;

const CASES: &[(&str, i32, i32, i32, i32)] = &[
    ("inside", 5, 1, 10, 5),
    ("below", -3, 0, 10, 0),
    ("above", 42, 0, 10, 10),
    ("at-low", 0, 0, 10, 0),
    ("at-high", 10, 0, 10, 10),
    ("equal-bounds", 7, 3, 3, 3),
    ("negative-range", -50, -20, -10, -20),
    ("zero", 0, -5, 5, 0),
    ("int-max", i32::MAX, -100, 100, 100),
    ("int-min", i32::MIN, -100, 100, -100),
    ("full-range", i32::MIN, i32::MIN, i32::MAX, i32::MIN),
];

#[test]
fn cases() {
    for &(name, value, low, high, want) in CASES {
        assert_eq!(clamp(value, low, high), want, "{name}");
    }
}

#[test]
fn same_as_ord_clamp() {
    for &(_, value, low, high, _) in CASES {
        assert_eq!(clamp(value, low, high), value.clamp(low, high));
    }
}
clamp.shI0RawGitHub
#!/usr/bin/env bash
# SPDX-License-Identifier: MIT
# Part of https://programming.tamnd.com/define-a-function/.

# clamp VALUE LOW HIGH
# Prints VALUE limited to the range from LOW to HIGH. A Bash function
# returns only an exit status from 0 to 255, so the result goes to the
# standard output, and the caller reads it with $( ).
clamp() {
  local value=$1 low=$2 high=$3
  if ((value < low)); then
    echo "$low"
  elif ((value > high)); then
    echo "$high"
  else
    echo "$value"
  fi
}
test_clamp.bats 19 lines
#!/usr/bin/env bats
# SPDX-License-Identifier: MIT
# Part of https://programming.tamnd.com/define-a-function/.

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

@test "inside" { run clamp 5 1 10; [ "$output" = "5" ]; }
@test "below" { run clamp -3 0 10; [ "$output" = "0" ]; }
@test "above" { run clamp 42 0 10; [ "$output" = "10" ]; }
@test "at-low" { run clamp 0 0 10; [ "$output" = "0" ]; }
@test "at-high" { run clamp 10 0 10; [ "$output" = "10" ]; }
@test "equal-bounds" { run clamp 7 3 3; [ "$output" = "3" ]; }
@test "negative-range" { run clamp -50 -20 -10; [ "$output" = "-20" ]; }
@test "zero" { run clamp 0 -5 5; [ "$output" = "0" ]; }
@test "int-max" { run clamp 2147483647 -100 100; [ "$output" = "100" ]; }
@test "int-min" { run clamp -2147483648 -100 100; [ "$output" = "-100" ]; }
@test "full-range" { run clamp -2147483648 -2147483648 2147483647; [ "$output" = "-2147483648" ]; }

References

  1. More Control Flow Tools, The Python Tutorial, 4.8 Defining Functions
  2. typing, Support for type hints, The Python Standard Library, the introduction
  3. function, MDN Web Docs JavaScript Reference, the introduction
  4. Everyday Types, The TypeScript Handbook, Parameter Type Annotations; Return Type Annotations
  5. Defining Methods, The Java Tutorials, the whole page
  6. Understanding Class Members, The Java Tutorials, Class Methods
  7. Methods, C# Programming Guide, Method signatures
  8. Static classes and static class members, C# Programming Guide, the introduction
  9. Functions, C reference, cppreference.com, the introduction
  10. Function declaration, C++ reference, cppreference.com, Function definition
  11. The Go Programming Language Specification, Function types; Function declarations; Exported identifiers
  12. Functions, The Rust Programming Language, Parameters; Functions with Return Values
  13. Shell Functions, Bash Reference Manual, 3.3 Shell Functions
  14. Bourne Shell Builtins, Bash Reference Manual, return
  15. Exit Status, Bash Reference Manual, the first paragraph
  16. Default parameters, MDN Web Docs JavaScript Reference, Description
  17. More on Functions, The TypeScript Handbook, Optional Parameters

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