类型 | 04 TypeScript中的逆变与协变
在 TypeScript
中,类型系统的一部分是关于如何处理函数参数和返回值的类型的。这就涉及到了 逆变(contravariant) 和 协变(covariant) 的概念。在TypeScript中学习协变性和逆变性可能有些棘手,但是了解它们对于理解类型和子类型是一个很好的补充。
在 TypeScript
中,类型系统的一部分是关于如何处理函数参数和返回值的类型的。这就涉及到了 逆变(contravariant) 和 协变(covariant) 的概念。在TypeScript中学习协变性和逆变性可能有些棘手,但是了解它们对于理解类型和子类型是一个很好的补充。
在 JavaScript 中将 ArrayBuffer 转换为字符串,可以使用 TextDecoder API。TextDecoder 可从字节序列中解码文本内容,支持多种编码格式。
Functions in a FP languages are first-class citizens. This means:
Restricted sense:
Wider sense:
OO focuses on the differences in the data, while FP concentrates on consistent data structures.
One main distinguishing characteristics of functional programming languages is that they describe what they want done, and not how to do it. OO, inside its methods, still uses mostly imperative techniques.
The most common informal way to understand imperative programs is as instruction sequences for a Von Neumann computer
Processor <---- bus ----> Memory
var sumOfSquares = function(list) {
var result = 0;
for (var i = 0; i < list.length; i++) {
result += square(list[i]);
}
return result;
};
console.log(sumOfSquares([2, 3, 5]));
var sumOfSquares = pipe(map(square), reduce(add, 0));
console.log(sumOfSquares([2, 3, 5]));
This calculates the odds of choosing the correct n
numbers out of the p
possibilities.
function odds(n, p) {
var acc = 1;
for(var i = 0; i < n; i++) {
acc *= (n - i) / (p - i);
}
return acc;
}
console.log(odds(3, 10)); //=> (3/10) * (2/9) * (1/8) => (1/120) => 0.008333...
// Recursive version
function odds(n, p) {
return (n == 0) ? 1 : (n / p) * odds(n - 1, p - 1);
}
console.log(odds(3, 10)); //=> (3/10) * (2/9) * (1/8) => (1/120) => 0.008333...
var odds = (function(){
var odds1 = function(n, p, acc) {
return (n == 0) ? acc : odds1(n - 1, p - 1, (n / p) * acc);
}
return function(n, p) {
return odds1(n, p, 1)
}
})();