(逼人手动挡哈哈哈哈哈哈哈哈哈、、、小核满载,大核围观hhh)
【编程范式(Programming paradigm)】 其实就是计算机编程所使用的方法,是设计程序结构所采用的设计风格。目前主流的编程范式有:命令式编程(Imperative programming)、函数式编程(Functional programming)、面向对象编程(Object-oriented programming)等
https://zhuanlan.zhihu.com/p/105224190
C语言是过程式编程语言;Java、C#是面向对象式编程语言;Haskell是函数式编程语言;而C则是多范式的编程语言。几个栗子:过程式:[C/C]#define COUNT_OF(ARR) (sizeof(ARR) / sizeof(*(ARR)))
int square(int x)
{
return x * x;
}
int main(void)
{
int numbers[] = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 };
int results[COUNT_OF(numbers)];
int i = 0;
for (; i < COUNT_OF(numbers); ++i)
{
results[i] = square(numbers[i]);
}
return 0;
}
面向对象:[C#]
interface CalcI
{
int Square(int x);
}
class Calculate : CalcI
{
public int Square(int x)
{
return x * x;
}
}
class Iteration
{
public int[] ForEach(int[] arr, CalcI cc)
{
int[] results = new int[arr.Length];
for (int i = 0; i < arr.Length; ++i)
{
results[i] = cc.Square(arr[i]);
}
return results;
}
}
class Program
{
static void Main(string[] args)
{
int[] numbers = new int[] { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 };
int[] results;
Calculate cc = new Calculate();
Iteration it = new Iteration();
results = it.ForEach(numbers, cc);
}
}
泛型:[C++]
template <typename T>
auto square(T x)
{
return x * x;
}
template <typename T, std::size_t N, typename F>
auto array_map(const T(& arr)[N], F fr)
{
std::array<T, N> res;
for (size_t i = 0; i < N; ++i)
{
res[i] = fr(arr[i]);
}
return res;
}
int main(void)
{
int numbers[] = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 };
auto results = array_map(numbers, square<std::remove_extent_t<decltype(numbers)>>);
return 0;
}
函数式:[F#]
let square x = x * x
let numbers = [1 .. 10]
let squares = List.map square numbers
模板元:[C++]
template <size_t X>
struct square
{
enum : size_t { value = X * X };
};
template <size_t... N>
struct array
{
enum : size_t { count = sizeof...(N) };
};
template <typename Arr, template <size_t> class F>
struct array_map;
template <template <size_t...> class Arr, size_t... N, template <size_t> class F>
struct array_map<Arr<N...>, F>
{
using type = Arr<F<N>::value...>;
};
int main(void)
{
using numbers = array<1, 2, 3, 4, 5, 6, 7, 8, 9, 10>;
using results = array_map<numbers, square>::type;
return 0;
}
可以看到,C++非常灵活,并不拘泥于某一种特定的编程方法论。一个编程语言属于某种类型,并不代表这个语言只能用那种思想编程。比如C语言,虽然是过程式,但我们仍然可以利用struct抽象出class的概念,用函数指针和算法模拟面向对象里的多态特征,只是会非常麻烦。而多范式语言则可以在它所支持的这些范式之间自由切换,不会有勉强的生涩感。当然,代价就是多范式语言一般相对复杂一些。
https://www.acwing.com/blog/content/16032/