5 种语言高阶函数最简示例(统一逻辑:平方、过滤偶数、求和)
2026/5/11 23:24:30 网站建设 项目流程

1. JavaScript 高阶函数

js

// map 平方 let arr = [1,2,3,4]; let res1 = arr.map(x => x*x); // filter 偶数 let res2 = arr.filter(x => x % 2 === 0); // reduce 求和 let res3 = arr.reduce((sum, x) => sum + x, 0); console.log(res1, res2, res3);

2. Java 8+ 高阶函数(Lambda)

java

运行

import java.util.Arrays; import java.util.List; import java.util.stream.Collectors; public class Test { public static void main(String[] args) { List<Integer> list = Arrays.asList(1,2,3,4); // map 平方 List<Integer> res1 = list.stream().map(x -> x*x).collect(Collectors.toList()); // filter 偶数 List<Integer> res2 = list.stream().filter(x -> x%2==0).collect(Collectors.toList()); // reduce 求和 int sum = list.stream().reduce(0, Integer::sum); } }

3. C# 高阶函数

csharp

运行

using System; using System.Linq; class Program { static void Main() { int[] arr = {1,2,3,4}; // map 平方 var res1 = arr.Select(x => x*x); // filter 偶数 var res2 = arr.Where(x => x%2 == 0); // reduce 求和 int sum = arr.Aggregate(0, (s,x) => s + x); } }

4. Go 语言 高阶函数

go

运行

package main import "fmt" // 高阶函数:函数当参数 func mapSlice(arr []int, f func(int)int) []int { res := make([]int, len(arr)) for i, v := range arr { res[i] = f(v) } return res } func main() { arr := []int{1,2,3,4} // 传匿名函数 res := mapSlice(arr, func(x int) int { return x * x }) fmt.Println(res) }

5. C++11 高阶函数

cpp

运行

#include <iostream> #include <vector> #include <algorithm> #include <numeric> using namespace std; int main() { vector<int> arr = {1,2,3,4}; vector<int> res; // transform 等价map transform(arr.begin(), arr.end(), back_inserter(res), [](int x){ return x*x; }); // 求和 reduce int sum = accumulate(arr.begin(), arr.end(), 0); return 0; }

需要专业的网站建设服务?

联系我们获取免费的网站建设咨询和方案报价,让我们帮助您实现业务目标

立即咨询