generalized type (math.)
Video: KCKCJY
In modern software development, generic programming has become a key technique for improving code quality, reusability and flexibility. As a parameterized polymorphic technique, generic types allow developers to use types as parameters when defining types or functions, thus creating generic code structures that can be applied to a wide range of data types. The benefits that come with generalization include:
Code reuse: the ability to define common algorithms and data structures that can operate on multiple types, reducing code redundancy.
type safety: supports more compile-time type checking, avoiding run-time type errors and enhancing program stability.
Performance Improvement: Generalization can also improve the efficiency of program execution by avoiding unnecessary type conversions.
Cangjie supports generic programming. Functions, structs, classes, interfaces, and extends can all introduce generic variants to generalize their functionality. The array type in Cangjie is a typical application of generic types, whose syntax is Array
In addition to types, we can also define generic functions. For example, we can use a generic function to implement concat for any two arrays of the same type. As shown in the following code, we define a generic function concat, and it supports any two Array
func concat
let defaultValue = if ( > 0) {
lhs[0]
} else if ( > 0) {
rhs[0]
} else {
return []
}
let newArr = Array
// Whole section copy using array slices
newArr[0..] = lhs
newArr[..+] = rhs
return newArr
}
The use of generics in conjunction with interfaces and subtypes also allows us to place specific constraints on the type variants in a generic, thus limiting the actual types of variants that can instantiate that type. In the following example, we want to look up the element element in the array arr. Although we don't care about the type of the array or its elements, the element type T must be able to support equality operations that allow us to compare elements in the array to a given element. Therefore, in the where clause of the lookup function, we require that T <: Equatable
func lookup
for (e in arr){
if (element == e){
return true
}
}
return false
}
The generic types of the hamlet do not support covariance. Take array as an example, arrays with different element types are completely different types, they cannot assign values to each other, even if the element types have parent-child type relationship is prohibited. This avoids type insecurity caused by array covariance.
As shown in the following example, Apple is a subclass of Fruit, but variables a and b cannot be assigned to each other, Array
open class Fruit {}
class Apple <: Fruit {}
main() {
var a: Array
var b: Array
a = b // compile error
b = a // compile error
}