Programming Search⌘K

Taskcore

Write a generic function

Also called generic method, function with a type parameter, bounded type parameter, type constraint, count the items greater than a value.

Write count_greater(items, limit), a function with a type parameter T and the constraint that values of T can be ordered, and use it to count the items of a list that are greater than a limit.

Task

Write a generic function count_greater(items, limit). It has a type parameter T. It takes a list of values of type T and one value limit of type T, and it returns how many items are greater than limit. An item that is equal to limit does not count. For example, count_greater([34, 50, 25, 100, 65], 50) is 2, because only 100 and 65 are greater than 50.

The body compares two values of type T, so T must be a type whose values can be ordered. Give the type parameter a constraint that says so. The Java tutorial uses this function to show why a constraint is necessary: without one, the method "does not compile because the greater than operator (>) applies only to primitive types"1. The fix is "a type parameter bounded by the Comparable interface"1.

The entry of the contract is count_greater(items, limit) with a list of integers. The list has from 0 to 10000 items, and each item and the limit fit in a signed 32-bit integer. The native tests also call the function with strings, so each solution must work for more than one type.

A generic function is the basic unit of generic programming, where "algorithms are written in terms of data types to-be-specified-later that are then instantiated when needed for specific types provided as parameters"2. Generics explains the idea, and Polymorphism compares it with the other kinds of polymorphism.

Solutions

Language The type parameter and its constraint The comparison
Python [T: Comparable], where Comparable is a Protocol with __lt__ limit < item
JavaScript no type parameter; the function takes any values item > limit
TypeScript <T extends number | string | bigint> item > limit
Java <T extends Comparable<T>> item.compareTo(limit) > 0
C# <T> with where T : IComparable<T> item.CompareTo(limit) > 0
C no type parameter; const void * and the size of an item a comparison function that the caller passes
C++ template <std::totally_ordered T> item > limit
Go [T cmp.Ordered] item > limit
Rust <T: PartialOrd> item > limit
  • Python. The function uses the type parameter syntax with an upper bound. The typing documentation shows the form class StrSequence[S: str], where S "is a TypeVar with a str upper bound"3. The bound "can be a concrete type, abstract type (ABC or Protocol), or even a union of types"3. The solution defines a Protocol with __lt__, so any type with < fits, because protocols give "structural subtyping (static duck-typing)"3. Python itself does not check the bound when the program runs: "Type variables exist primarily for the benefit of static type checkers"3.
  • JavaScript. The language has no type parameters, so every function is generic. > works on numbers and on strings. "If both values are strings, they are compared as strings, based on the values of the UTF-16 code units (not Unicode code points) they contain"4. Nothing stops a call with a mix of types, which the pitfalls below show.
  • TypeScript. A constraint uses extends. The handbook says that to limit a type parameter, "we must list our requirement as a constraint on what Type can be"5. The solution limits T to the primitive types that > orders. The types are erased when the program runs, so the JavaScript that runs is the same as the JavaScript solution.
  • Java. "Generic methods are methods that introduce their own type parameters"6. The solution is the tutorial's method with a List in place of an array: <T extends Comparable<T>> lets the body call compareTo, because "You cannot use the > operator to compare objects"1. Integer and String both implement Comparable.
  • C#. "Constraints inform the compiler about the capabilities a type argument must have"7. The guide names the constraint for an ordering: "apply the where T : IEquatable or where T : IComparable constraint"7. int and string implement IComparable<T>. The solution compares strings with CompareTo, which uses the rules of the current culture, so the tests use only lowercase ASCII words.
  • C. C has no type parameters. The standard function qsort shows the usual way to write code for any type: it takes a pointer to the items, the count, the size of one item and a comparison function. "Function pointed to by comp is used for object comparison"8. The solution has the same shape, and count_greater_int is the entry for int.
  • C++. A function template takes a type parameter, and a concept limits it. "Each concept is a predicate, evaluated at compile time, and becomes a part of the interface of a template where it is used as a constraint"9. The solution uses std::totally_ordered, which "specifies that the comparison operators ==,!=,<,>,<=,>= on a type yield results consistent with a strict total order on the type"10.
  • Go. "Each type parameter has a type constraint that acts as a kind of meta-type for the type parameter"11. The solution uses cmp.Ordered, which "is a constraint that permits any ordered type: any type that supports the operators < <= >= >"12.
  • Rust. The Rust book builds a generic largest function, and the first version does not compile. The fix is to "restrict the types valid for T to only those that implement PartialOrd"13. The solution uses the same bound. The function takes &[T] and &T, so it does not need to copy or own the items.

One function, several types

The Python solution works for any type with <. Here the same function counts integers, strings and dates:

from collections.abc import Iterable
from datetime import date
from typing import Protocol, Self


class Comparable(Protocol):
    def __lt__(self, other: Self, /) -> bool: ...


def count_greater[T: Comparable](items: Iterable[T], limit: T) -> int:
    return sum(1 for item in items if limit < item)


print(count_greater([34, 50, 25, 100, 65], 50))
print(count_greater(["pear", "apple", "plum"], "orange"))
print(count_greater([date(2024, 1, 5), date(2025, 3, 1)], date(2024, 12, 31)))
Output
2
2
1

"pear" and "plum" come after "orange" in the order of the code points, and one of the two dates is after the end of 2024.

Edge cases

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

  • empty: an empty list has no item greater than the limit, so the result is 0.
  • equal-not-counted: [5, 5, 5] with the limit 5 gives 0, because the comparison is strict.
  • duplicates: each copy of a value counts, so [7, 1, 7, 7] with the limit 6 gives 3.
  • negative: [-3, -1, 0, 2] with the limit -2 gives 3.
  • min-limit: with the limit -2147483648, the smallest 32-bit integer, every other item counts. A comparison that subtracts the two values overflows here.
  • max-limit: no 32-bit integer is greater than 2147483647, so the result is 0.
  • single: [1] with the limit 0 gives 1.

Pitfalls

A type parameter with no constraint

Without a constraint, the compiler knows nothing about T, so it does not allow >. The Rust book shows the error for its largest function13:

This code does not compile, on purpose.

fn count_greater<T>(items: &[T], limit: &T) -> usize {
    items.iter().filter(|item| *item > limit).count()
}

fn main() {
    println!("{}", count_greater(&[1, 5, 9], &4));
}

The error is E0369: the binary operation > cannot be applied to &T. Add the bound T: PartialOrd. Java gives the same kind of error for > on a T, and C# and Go do too, because the operator is not in the constraint.

Numbers kept as strings

In JavaScript, the function takes values of any type. When the items and the limit are strings, > compares them as strings4, so "10" is less than "9":

This code runs but gives a wrong answer on purpose.

function countGreater(items, limit) {
  return items.filter((item) => item > limit).length;
}

console.log(countGreater(["10", "9", "100"], "9"));
console.log(countGreater([10, 9, 100], 9));
Output
0
2

Convert the input to numbers before the call. In TypeScript, the constraint does not stop this case either, because string is one of the allowed types. A call with a number list and a string limit is a type error in TypeScript, because both must have the same type T.

NaN in a list of floats

cmp.Ordered in Go and PartialOrd in Rust allow floating-point types. "Note that floating-point types may contain NaN ("not-a-number") values. An operator such as == or < will always report false when comparing a NaN value with any other value, NaN or not."12 So a NaN item never counts, and a NaN limit gives 0:

This code runs but gives a wrong answer on purpose.

package main

import (
	"cmp"
	"fmt"
	"math"
)

func CountGreater[T cmp.Ordered](items []T, limit T) int {
	n := 0
	for _, item := range items {
		if item > limit {
			n++
		}
	}
	return n
}

func main() {
	nan := math.NaN()
	fmt.Println(CountGreater([]float64{1, nan, 3}, 0))
	fmt.Println(CountGreater([]float64{1, 2, 3}, nan))
}
Output
2
0

If the data can hold NaN, decide what it means, and test for it with math.IsNaN before the call. In C++, std::totally_ordered requires a total order, which NaN breaks, so a call with NaN values breaks the requirement of the concept10.

A comparison function that subtracts

In C, the comparison function returns a negative number, zero or a positive number. return a - b; is short, but it can overflow. The cppreference example of qsort marks it as an "erroneous shortcut: undefined behavior in case of integer overflow, such as with INT_MIN here"8. Compare with < and >, as the solution does. The case min-limit catches the error.

Code

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

count_greater.pyI0RawGitHub
# SPDX-License-Identifier: MIT
# Part of https://programming.tamnd.com/write-a-generic-function/.

from collections.abc import Iterable
from typing import Protocol, Self


class Comparable(Protocol):
    """A type whose values can be ordered with <."""

    def __lt__(self, other: Self, /) -> bool: ...


def count_greater[T: Comparable](items: Iterable[T], limit: T) -> int:
    """Return how many items are greater than limit."""
    return sum(1 for item in items if limit < item)
test_count_greater.py 33 lines
# SPDX-License-Identifier: MIT
# Part of https://programming.tamnd.com/write-a-generic-function/.

import pytest

from count_greater import count_greater

CASES = {
    "some": ([34, 50, 25, 100, 65], 50, 2),
    "all": ([3, 4, 5], 2, 3),
    "none": ([3, 4, 5], 9, 0),
    "empty": ([], 0, 0),
    "equal-not-counted": ([5, 5, 5], 5, 0),
    "duplicates": ([7, 1, 7, 7], 6, 3),
    "negative": ([-3, -1, 0, 2], -2, 3),
    "min-limit": ([-2147483648, 0, 2147483647], -2147483648, 2),
    "max-limit": ([2147483647, 1], 2147483647, 0),
    "single": ([1], 0, 1),
}


@pytest.mark.parametrize("name", CASES)
def test_count_greater(name):
    items, limit, want = CASES[name]
    assert count_greater(items, limit) == want


def test_strings():
    assert count_greater(["pear", "apple", "plum"], "orange") == 2


def test_floats():
    assert count_greater([0.5, 1.5, 2.5], 1.0) == 2
count_greater.cppI0RawGitHub
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/write-a-generic-function/.

#include "count_greater.hpp"

namespace generic {

std::size_t count_greater_int(const std::vector<int>& items, int limit) {
    return count_greater(items, limit);
}

}  // namespace generic
count_greater.hpp 30 lines
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/write-a-generic-function/.

#ifndef COUNT_GREATER_HPP
#define COUNT_GREATER_HPP

#include <concepts>
#include <cstddef>
#include <vector>

namespace generic {

// Returns how many items are greater than limit.
template <std::totally_ordered T>
std::size_t count_greater(const std::vector<T>& items, const T& limit) {
    std::size_t n = 0;
    for (const T& item : items) {
        if (item > limit) {
            ++n;
        }
    }
    return n;
}

// The entry for int.
std::size_t count_greater_int(const std::vector<int>& items, int limit);

}  // namespace generic

#endif
test_count_greater.cpp 56 lines
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/write-a-generic-function/.

#include <climits>
#include <cstddef>
#include <cstdio>
#include <string>
#include <vector>

#include "count_greater.hpp"

namespace {

struct test_case {
    const char* name;
    std::vector<int> items;
    int limit;
    std::size_t want;
};

const test_case cases[] = {
    {"some", {34, 50, 25, 100, 65}, 50, 2},
    {"all", {3, 4, 5}, 2, 3},
    {"none", {3, 4, 5}, 9, 0},
    {"empty", {}, 0, 0},
    {"equal-not-counted", {5, 5, 5}, 5, 0},
    {"duplicates", {7, 1, 7, 7}, 6, 3},
    {"negative", {-3, -1, 0, 2}, -2, 3},
    {"min-limit", {INT_MIN, 0, INT_MAX}, INT_MIN, 2},
    {"max-limit", {INT_MAX, 1}, INT_MAX, 0},
    {"single", {1}, 0, 1},
};

}  // namespace

int main() {
    int failures = 0;
    for (const auto& c : cases) {
        const std::size_t got = generic::count_greater_int(c.items, c.limit);
        if (got != c.want) {
            std::printf("FAIL %s: got %zu, want %zu\n", c.name, got, c.want);
            ++failures;
        }
    }
    const std::vector<std::string> words{"pear", "apple", "plum"};
    const std::size_t got = generic::count_greater(words, std::string("orange"));
    if (got != 2) {
        std::printf("FAIL strings: got %zu, want 2\n", got);
        ++failures;
    }
    if (failures != 0) {
        return 1;
    }
    std::printf("ok\n");
    return 0;
}
CountGreater.javaI0RawGitHub
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/write-a-generic-function/.

import java.util.List;

/** A generic method with a bounded type parameter. */
public final class CountGreater {
    private CountGreater() {}

    /** Returns how many items are greater than limit. */
    public static <T extends Comparable<T>> int countGreater(List<T> items, T limit) {
        int count = 0;
        for (T item : items) {
            if (item.compareTo(limit) > 0) {
                count++;
            }
        }
        return count;
    }
}
CountGreaterTest.java 39 lines
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/write-a-generic-function/.

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

import java.util.List;
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 CountGreaterTest {
    static Stream<Arguments> cases() {
        return Stream.of(
                Arguments.of("some", List.of(34, 50, 25, 100, 65), 50, 2),
                Arguments.of("all", List.of(3, 4, 5), 2, 3),
                Arguments.of("none", List.of(3, 4, 5), 9, 0),
                Arguments.of("empty", List.of(), 0, 0),
                Arguments.of("equal-not-counted", List.of(5, 5, 5), 5, 0),
                Arguments.of("duplicates", List.of(7, 1, 7, 7), 6, 3),
                Arguments.of("negative", List.of(-3, -1, 0, 2), -2, 3),
                Arguments.of("min-limit", List.of(Integer.MIN_VALUE, 0, Integer.MAX_VALUE), Integer.MIN_VALUE, 2),
                Arguments.of("max-limit", List.of(Integer.MAX_VALUE, 1), Integer.MAX_VALUE, 0),
                Arguments.of("single", List.of(1), 0, 1)
        );
    }

    @ParameterizedTest(name = "{0}")
    @MethodSource("cases")
    void countGreater(String name, List<Integer> items, int limit, int want) {
        assertEquals(want, CountGreater.countGreater(items, limit));
    }

    @Test
    void strings() {
        assertEquals(2, CountGreater.countGreater(List.of("pear", "apple", "plum"), "orange"));
    }
}
count_greater.cI0RawGitHub
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/write-a-generic-function/.

#include "count_greater.h"

size_t count_greater(const void *items, size_t count, size_t size, const void *limit,
                     int (*cmp)(const void *, const void *)) {
    const unsigned char *p = items;
    size_t n = 0;
    for (size_t i = 0; i < count; i++) {
        if (cmp(p + i * size, limit) > 0) {
            n++;
        }
    }
    return n;
}

int compare_ints(const void *a, const void *b) {
    int x = *(const int *)a;
    int y = *(const int *)b;
    return (x > y) - (x < y);
}

size_t count_greater_int(const int *items, size_t count, int limit) {
    return count_greater(items, count, sizeof *items, &limit, compare_ints);
}
count_greater.h 20 lines
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/write-a-generic-function/.

#ifndef COUNT_GREATER_H
#define COUNT_GREATER_H

#include <stddef.h>

// Returns how many of the count items, each size bytes, compare greater than limit.
// cmp returns a negative number, zero or a positive number, as for qsort.
size_t count_greater(const void *items, size_t count, size_t size, const void *limit,
                     int (*cmp)(const void *, const void *));

// Compares two ints without subtraction, so INT_MIN does not overflow.
int compare_ints(const void *a, const void *b);

// The entry for int: count_greater with compare_ints.
size_t count_greater_int(const int *items, size_t count, int limit);

#endif
test_count_greater.c 57 lines
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/write-a-generic-function/.

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

#include "count_greater.h"

struct test_case {
    const char *name;
    int items[5];
    size_t count;
    int limit;
    size_t want;
};

static const struct test_case cases[] = {
    {"some", {34, 50, 25, 100, 65}, 5, 50, 2},
    {"all", {3, 4, 5}, 3, 2, 3},
    {"none", {3, 4, 5}, 3, 9, 0},
    {"empty", {0}, 0, 0, 0},
    {"equal-not-counted", {5, 5, 5}, 3, 5, 0},
    {"duplicates", {7, 1, 7, 7}, 4, 6, 3},
    {"negative", {-3, -1, 0, 2}, 4, -2, 3},
    {"min-limit", {INT_MIN, 0, INT_MAX}, 3, INT_MIN, 2},
    {"max-limit", {INT_MAX, 1}, 2, INT_MAX, 0},
    {"single", {1}, 1, 0, 1},
};

static int compare_strings(const void *a, const void *b) {
    return strcmp(*(const char *const *)a, *(const char *const *)b);
}

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];
        size_t got = count_greater_int(c->items, c->count, c->limit);
        if (got != c->want) {
            printf("FAIL %s: got %zu, want %zu\n", c->name, got, c->want);
            failures++;
        }
    }
    const char *words[] = {"pear", "apple", "plum"};
    const char *limit = "orange";
    size_t got = count_greater(words, 3, sizeof words[0], &limit, compare_strings);
    if (got != 2) {
        printf("FAIL strings: got %zu, want 2\n", got);
        failures++;
    }
    if (failures != 0) {
        return 1;
    }
    printf("ok\n");
    return 0;
}
CountGreater.csI0RawGitHub
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/write-a-generic-function/.

using System;
using System.Collections.Generic;

/// <summary>A generic method with a constraint on its type parameter.</summary>
public static class Generic
{
    /// <summary>Returns how many items are greater than limit.</summary>
    public static int CountGreater<T>(IEnumerable<T> items, T limit)
        where T : IComparable<T>
    {
        int count = 0;
        foreach (T item in items)
        {
            if (item.CompareTo(limit) > 0)
            {
                count++;
            }
        }
        return count;
    }
}
CountGreaterTests.cs 35 lines
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/write-a-generic-function/.

using Xunit;

public sealed class CountGreaterTests
{
    public static TheoryData<string, int[], int, int> Cases => new()
    {
        { "some", new[] { 34, 50, 25, 100, 65 }, 50, 2 },
        { "all", new[] { 3, 4, 5 }, 2, 3 },
        { "none", new[] { 3, 4, 5 }, 9, 0 },
        { "empty", new int[0], 0, 0 },
        { "equal-not-counted", new[] { 5, 5, 5 }, 5, 0 },
        { "duplicates", new[] { 7, 1, 7, 7 }, 6, 3 },
        { "negative", new[] { -3, -1, 0, 2 }, -2, 3 },
        { "min-limit", new[] { int.MinValue, 0, int.MaxValue }, int.MinValue, 2 },
        { "max-limit", new[] { int.MaxValue, 1 }, int.MaxValue, 0 },
        { "single", new[] { 1 }, 0, 1 },
    };

    [Theory]
    [MemberData(nameof(Cases))]
    public void CountGreater(string name, int[] items, int limit, int want)
    {
        Assert.NotNull(name);
        Assert.Equal(want, Generic.CountGreater(items, limit));
    }

    [Fact]
    public void Strings()
    {
        Assert.Equal(2, Generic.CountGreater(new[] { "pear", "apple", "plum" }, "orange"));
    }
}
count-greater.jsI0RawGitHub
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/write-a-generic-function/.

/** Returns how many items are greater than limit. The items and limit must be of one type that > orders. */
export function countGreater(items, limit) {
  let count = 0;
  for (const item of items) {
    if (item > limit) {
      count++;
    }
  }
  return count;
}
count-greater.test.js 30 lines
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/write-a-generic-function/.

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

import { countGreater } from "./count-greater.js";

const cases = [
  ["some", [34, 50, 25, 100, 65], 50, 2],
  ["all", [3, 4, 5], 2, 3],
  ["none", [3, 4, 5], 9, 0],
  ["empty", [], 0, 0],
  ["equal-not-counted", [5, 5, 5], 5, 0],
  ["duplicates", [7, 1, 7, 7], 6, 3],
  ["negative", [-3, -1, 0, 2], -2, 3],
  ["min-limit", [-2147483648, 0, 2147483647], -2147483648, 2],
  ["max-limit", [2147483647, 1], 2147483647, 0],
  ["single", [1], 0, 1],
];

for (const [name, items, limit, want] of cases) {
  test(name, () => {
    assert.equal(countGreater(items, limit), want);
  });
}

test("strings", () => {
  assert.equal(countGreater(["pear", "apple", "plum"], "orange"), 2);
});
count-greater.tsI0RawGitHub
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/write-a-generic-function/.

/** Returns how many items are greater than limit. */
export function countGreater<T extends number | string | bigint>(items: readonly T[], limit: T): number {
  let count = 0;
  for (const item of items) {
    if (item > limit) {
      count++;
    }
  }
  return count;
}
count-greater.test.ts 34 lines
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/write-a-generic-function/.

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

import { countGreater } from "./count-greater.ts";

const cases: [string, number[], number, number][] = [
  ["some", [34, 50, 25, 100, 65], 50, 2],
  ["all", [3, 4, 5], 2, 3],
  ["none", [3, 4, 5], 9, 0],
  ["empty", [], 0, 0],
  ["equal-not-counted", [5, 5, 5], 5, 0],
  ["duplicates", [7, 1, 7, 7], 6, 3],
  ["negative", [-3, -1, 0, 2], -2, 3],
  ["min-limit", [-2147483648, 0, 2147483647], -2147483648, 2],
  ["max-limit", [2147483647, 1], 2147483647, 0],
  ["single", [1], 0, 1],
];

for (const [name, items, limit, want] of cases) {
  test(name, () => {
    assert.equal(countGreater(items, limit), want);
  });
}

test("strings", () => {
  assert.equal(countGreater(["pear", "apple", "plum"], "orange"), 2);
});

test("bigints", () => {
  assert.equal(countGreater([1n, 2n ** 70n], 2n ** 64n), 1);
});
count_greater.goI0RawGitHub
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/write-a-generic-function/.

// Package generic has a function with a constrained type parameter.
package generic

import "cmp"

// CountGreater returns how many items are greater than limit.
func CountGreater[T cmp.Ordered](items []T, limit T) int {
	n := 0
	for _, item := range items {
		if item > limit {
			n++
		}
	}
	return n
}
count_greater_test.go 43 lines
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/write-a-generic-function/.

package generic

import (
	"math"
	"testing"
)

var cases = []struct {
	name  string
	items []int32
	limit int32
	want  int
}{
	{"some", []int32{34, 50, 25, 100, 65}, 50, 2},
	{"all", []int32{3, 4, 5}, 2, 3},
	{"none", []int32{3, 4, 5}, 9, 0},
	{"empty", nil, 0, 0},
	{"equal-not-counted", []int32{5, 5, 5}, 5, 0},
	{"duplicates", []int32{7, 1, 7, 7}, 6, 3},
	{"negative", []int32{-3, -1, 0, 2}, -2, 3},
	{"min-limit", []int32{math.MinInt32, 0, math.MaxInt32}, math.MinInt32, 2},
	{"max-limit", []int32{math.MaxInt32, 1}, math.MaxInt32, 0},
	{"single", []int32{1}, 0, 1},
}

func TestCountGreater(t *testing.T) {
	for _, c := range cases {
		t.Run(c.name, func(t *testing.T) {
			if got := CountGreater(c.items, c.limit); got != c.want {
				t.Fatalf("got %d, want %d", got, c.want)
			}
		})
	}
}

func TestStrings(t *testing.T) {
	if got := CountGreater([]string{"pear", "apple", "plum"}, "orange"); got != 2 {
		t.Fatalf("got %d, want 2", got)
	}
}
count_greater.rsI0RawGitHub
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/write-a-generic-function/.

/// Returns how many items are greater than limit.
pub fn count_greater<T: PartialOrd>(items: &[T], limit: &T) -> usize {
    items.iter().filter(|item| *item > limit).count()
}
tests/count_greater_test.rs 29 lines
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/write-a-generic-function/.

use algo_write_a_generic_function::count_greater;

const CASES: &[(&str, &[i32], i32, usize)] = &[
    ("some", &[34, 50, 25, 100, 65], 50, 2),
    ("all", &[3, 4, 5], 2, 3),
    ("none", &[3, 4, 5], 9, 0),
    ("empty", &[], 0, 0),
    ("equal-not-counted", &[5, 5, 5], 5, 0),
    ("duplicates", &[7, 1, 7, 7], 6, 3),
    ("negative", &[-3, -1, 0, 2], -2, 3),
    ("min-limit", &[i32::MIN, 0, i32::MAX], i32::MIN, 2),
    ("max-limit", &[i32::MAX, 1], i32::MAX, 0),
    ("single", &[1], 0, 1),
];

#[test]
fn count_greater_cases() {
    for &(name, items, limit, want) in CASES {
        assert_eq!(count_greater(items, &limit), want, "{name}");
    }
}

#[test]
fn strings() {
    assert_eq!(count_greater(&["pear", "apple", "plum"], &"orange"), 2);
}

References

  1. Generic Methods and Bounded Type Parameters, The Java Tutorials, Whole page
  2. Generic programming, Wikipedia, Introduction
  3. typing, Python 3.14 documentation, TypeVar; Protocol
  4. Less than (<), MDN Web Docs, Description
  5. Generics, The TypeScript Handbook, Generic Constraints
  6. Generic Methods, The Java Tutorials, Whole page
  7. Constraints on type parameters, C# programming guide, Introduction; Constraints on reference types
  8. qsort, qsort_s, C reference, cppreference.com, Description; Example
  9. Constraints and concepts, C++ reference, cppreference.com, Introduction
  10. std::totally_ordered, C++ reference, cppreference.com, Description
  11. Tutorial: Getting started with generics, The Go Programming Language, Add a generic function to handle multiple types
  12. Package cmp, Go standard library, type Ordered
  13. Generic Data Types, The Rust Programming Language, In Function Definitions

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 (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