First-Class Callables

Functions as values — PHP 8.1's ... syntax against passing behavior as data in 10 languages.

C C23

C23
#include <stdio.h>

/* C's "function as a value" is the function pointer: no closure, the callee
   receives no environment beyond the pointer itself */
static int square(int x) { return x * x; }
static int cube(int x) { return x * x * x; }

static void map(const int *xs, int n, int (*f)(int)) {
    for (int i = 0; i < n; i++) printf(i ? ", %d" : "%d", f(xs[i]));
    printf("\n");
}

int main(void) {
    int xs[] = {1, 2, 3};
    map(xs, 3, square);   /* pass the function itself */
    map(xs, 3, cube);
    return 0;
}
Output
1, 4, 9
1, 8, 27

C++ C++26

C++26
#include <cstdio>
#include <vector>
#include <algorithm>

int main() {
    std::vector<int> xs{3, 1, 2};
    // a lambda is a value with its own captured environment
    auto square = [](int x) { return x * x; };
    std::transform(xs.begin(), xs.end(), xs.begin(), square);
    for (std::size_t i = 0; i < xs.size(); i++) std::printf(i ? ", %d" : "%d", xs[i]);
    std::printf("\n");
    std::sort(xs.begin(), xs.end(), [](int a, int b) { return a > b; });
    for (std::size_t i = 0; i < xs.size(); i++) std::printf(i ? ", %d" : "%d", xs[i]);
    std::printf("\n");
    return 0;
}
Output
9, 1, 4
9, 4, 1

C# v11.0.100

v11.0.100
using System;
using System.Linq;
using System.Collections.Generic;

Func<int, int> square = x => x * x; // a delegate wraps any callable
Console.WriteLine(square(5));
var doubled = new[] { 1, 2, 3 }.Select(x => x * 2);
Console.WriteLine(string.Join(",", doubled));
var names = new List<string> { "bob", "al" };
names.Sort((a, b) => a.Length - b.Length);
Console.WriteLine(string.Join(",", names));
Output
25
2,4,6
al,bob

Go v1.27.4

v1.27.4
package main

import (
	"fmt"
	"sort"
)

func apply(f func(int) int, xs []int) []int {
	out := make([]int, len(xs))
	for i, x := range xs {
		out[i] = f(x)
	}
	return out
}

func main() {
	double := func(x int) int { return x * 2 } // a function value
	fmt.Println(apply(double, []int{1, 2, 3}))
	xs := []string{"bb", "a"}
	sort.Slice(xs, func(i, j int) bool { return len(xs[i]) < len(xs[j]) })
	fmt.Println(xs)
}
Output
[2 4 6]
[a bb]

Java v27.0.1

v27.0.1
import java.util.List;
import java.util.function.Function;
import java.util.stream.Collectors;

public class Main {
    static String shout(String s) { return s.toUpperCase() + "!"; }

    public static void main(String[] args) {
        Function<String, String> ref = Main::shout; // method reference
        System.out.println(ref.apply("hey"));
        Function<Integer, Integer> square = x -> x * x; // lambda
        System.out.println(square.apply(5));
        List<Integer> xs = List.of(3, 1, 2);
        String sorted = xs.stream().sorted().map(String::valueOf)
                .collect(Collectors.joining(" "));
        System.out.println(sorted);
    }
}
Output
HEY!
25
1 2 3

JavaScript v26.13.1

v26.13.1
const square = (x) => x * x;       // arrow functions are values
console.log(square(5));
const shout = function (s) { return s.toUpperCase() + "!"; };
console.log([1, 2, 3].map(square).join(","));
console.log(["bb", "a"].sort((a, b) => a.length - b.length).join(","));
console.log(shout("hey"));
Output
25
1,4,9
a,bb
HEY!

PHP v8.6.0

v8.6.0
// first-class callable: `...` turns a callable expression into a Closure
$len = strlen(...);
echo $len("abc"), "\n";

$upper = strtoupper(...);
$shout = fn(string $s): string => $upper($s) . "!";
echo $shout("hey"), "\n";

// callables flow through higher-order functions as plain values
function apply(callable $f, array $xs): array { return array_map($f, $xs); }
$double = fn(int $n): int => $n * 2;
echo implode(",", apply($double, [1, 2, 3])), "\n";

// method-call syntax also produces a first-class callable
class Greeter {
    public function greet(string $name): string { return "hi $name"; }
}
$g = (new Greeter)->greet(...);
echo $g("php"), "\n";
echo get_class($len), "\n";
Output
3
HEY!
2,4,6
hi php
Closure

Python v3.15.2

v3.15.2
def square(x):
    return x * x

double = lambda x: x * 2  # any function is a first-class value

def apply(f, xs):
    return [f(x) for x in xs]

print(square(5))
print(apply(double, [1, 2, 3]))
print(sorted(["bb", "a"], key=len))
print(apply(square, [1, 2, 3]))
Output
25
[2, 4, 6]
['a', 'bb']
[1, 4, 9]

Rust v1.99.1

v1.99.1
fn apply(f: fn(i32) -> i32, xs: &[i32]) -> Vec<i32> {
    xs.iter().map(|x| f(*x)).collect()
}

fn main() {
    let square = |x: i32| x * x; // closure value
    println!("{:?}", vec![1, 2, 3].into_iter().map(square).collect::<Vec<_>>());
    let double = |x: i32| x * 2;
    println!("{:?}", apply(double, &[1, 2, 3]));
    let mut names = vec!["bb", "a"];
    names.sort_by_key(|s| s.len());
    println!("{:?}", names);
}
Output
[1, 4, 9]
[2, 4, 6]
["a", "bb"]

TypeScript v26.13.1

v26.13.1
// arrow functions are first-class values: assign, pass, return freely
const square = (x: number): number => x * x;

function apply(xs: number[], f: (x: number) => number): number[] {
  return xs.map(f);
}
console.log(square(5));
console.log(apply([1, 2, 3], square));
const shout = (s: string): string => s.toUpperCase() + "!";
console.log(shout("hey"));
Output
25
[ 1, 4, 9 ]
HEY!

Language differences

C: function pointers (example): the most primitive form of functions-as-values — just an address, no environment; qsort's comparator is the classic use, and callbacks that need context must carry their own void*.

C++: lambdas with captures (example): a lambda is a value carrying its captured environment, storable in std::function or passed straight into templates; adds the closure dimension over C function pointers with zero cost (inlined).

C#: delegates and lambdas (example): Func/Action unify any callable behind one representation, and LINQ is built on flowing behavior through parameters.

Go: function values (example): functions are first-class types, and func(int) int works as parameter, field, or return value; standard libraries like sort.Slice make closures the primary API shape.

Java: method references and lambdas (example): Main::shout and x -> x*x are both instances of functional interfaces; before Java 8, behavior had to travel wrapped in anonymous inner classes.

JavaScript: functions are values by birth (example): arrow, anonymous, and named functions all assign and pass freely; map/sort's higher-order APIs are daily routine.

PHP: the 8.1+ first-class callable syntax (example): strlen(...) turns any callable expression into a Closure (equivalent to Closure::fromCallable), and $obj->m(...) does the same for methods; friendlier to static analysis than the old string/array callables and it locks the scope of the creation site; usable in constant expressions since 8.5, with ? placeholders for partial application since 8.6.

Python: function objects (example): def and lambda both produce objects you can assign, pass, and attach attributes to; map and sorted(key=) are standard habits.

Rust: closures plus fn pointers, a dual track (example): closures implement Fn/FnMut/FnOnce according to their captures; capture-free closures degrade to fn pointers, and iterator adapters (map/sort_by_key) feed on closures.

TypeScript: same mechanics as JS (example): function types like (x: number) => number make higher-order signatures explicit — behavior parameters get a compile-time shape.