一等函数与回调

函数是值——PHP 8.1 ... 语法与 10 语言「把行为当数据传」对照。

C C23

C23
#include <stdio.h>

/* C 的「函数是值」就是函数指针:没有闭包,
   被调方除了指针本身拿不到任何环境 */
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);   /* 把函数本身传进去 */
    map(xs, 3, cube);
    return 0;
}
输出
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};
    // lambda 是携带自身捕获环境的值
    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;
}
输出
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; // 委托包装任意可调用
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));
输出
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 } // 函数值
	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)
}
输出
[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; // 方法引用
        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);
    }
}
输出
HEY!
25
1 2 3

JavaScript v26.13.1

v26.13.1
const square = (x) => x * x;       // 箭头函数是值
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"));
输出
25
1,4,9
a,bb
HEY!

PHP v8.6.0

v8.6.0
// 一等可调用:`...` 把可调用表达式变成 Closure
$len = strlen(...);
echo $len("abc"), "\n";

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

// 可调用作为普通值流经高阶函数
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";

// 方法调用语法同样产出一等可调用
class Greeter {
    public function greet(string $name): string { return "hi $name"; }
}
$g = (new Greeter)->greet(...);
echo $g("php"), "\n";
echo get_class($len), "\n";
输出
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  # 任何函数都是一等值

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]))
输出
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; // 闭包值
    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);
}
输出
[1, 4, 9]
[2, 4, 6]
["a", "bb"]

TypeScript v26.13.1

v26.13.1
// 箭头函数是一等值:赋值、传参、返回皆可
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"));
输出
25
[ 1, 4, 9 ]
HEY!

语言差异说明

C:函数指针(示例):「函数是值」的最原始形态——只有地址,没有环境;qsort 的比较器是经典用法,回调要上下文得自己带 void*。

C++:lambda + 捕获(示例):lambda 是带捕获环境的值,可塞进 std::function 或直接传模板;比 C 函数指针多了闭包维度,且零开销(内联)。

C#:委托与 lambda(示例):Func/Action 统一可调用表示,LINQ 全靠它把行为当参数流转。

Go:函数值(示例):函数是类型的一等公民,func(int) int 可作参数/字段/返回值;sort.Slice 等标准库以闭包为 API 主形态。

Java:方法引用 + lambda(示例):Main::shout 与 x -> x*x 都是函数式接口的实例;在 8 引入 lambda 之前,行为只能靠匿名内部类包装。

JavaScript:函数本就是值(示例):箭头/匿名/具名函数皆可赋值传参;map/sort 的高阶 API 是语言日常。

PHP:8.1+ 一等可调用语法(示例):strlen(...) 把任意可调用表达式变成 Closure(等价 Closure::fromCallable),方法调用 $obj->m(...) 同理;比旧的字符串/数组 callable 更利于静态分析,且锁定创建处作用域;8.5 起可进常量表达式,8.6 起 ? 占位符支持部分应用。

Python:函数对象(示例):def/lambda 产物皆对象,可赋值、传参、挂属性;map/sorted(key=) 高阶用法是标准习惯。

Rust:闭包 + fn 指针双轨(示例):闭包按捕获实现 Fn/FnMut/FnOnce 三 trait;无捕获闭包可退化为 fn 指针,迭代器适配器(map/sort_by_key)以闭包为食。

TypeScript:与 JS 同机制(示例):函数类型 (x: number) => number 让高阶签名显式化——行为参数有了编译期形状。