strangerRidingCaml
7. Subtyping and Variance 본문
Subtyping and Variance
Subtyping is a relationship between types where one type is considered a subtype of another type.
This relationship is often denoted as S <: T, meaning that type S is a subtype of type T.
Subtyping allows for more flexible type systems where a value of a subtype can be used wherever a value of its supertype is expected.
Variance is a property of type constructors, such as generic types or function types, that determines how the subtyping relationship is inherited by the constructed types.
There are three main variance annotations: covariant, contravariant, and invariant.
- Covariant types preserve the subtyping relationship. For example, if S <: T, then List[S] <: List[T].
- Contravariant types reverse the subtyping relationship. For example, if S <: T, then Function[T] <: Function[S].
- Invariant types do not change the subtyping relationship. For example, List[T] is invariant in T.
Lab Activity: Implementing Subtyping and Variance
Let's implement a simple example of subtyping and variance in Python using classes and inheritance.
class Animal:
def speak(self):
print("Animal speaks")
class Dog(Animal):
def speak(self):
print("Dog barks")
def speak(animal):
animal.speak()
def main():
animal = Animal()
dog = Dog()
speak(animal)
speak(dog)
if __name__ == "__main__":
main()
In the lab activity, we define a base class `Animal` with a method `speak`.
We then define a subclass `Dog` that inherits from `Animal` and overrides the `speak` method.
We demonstrate subtyping by passing instances of both `Animal` and `Dog` to a function expecting an `Animal`.
'Type theory' 카테고리의 다른 글
9. System F: Introduction to Polymorphic Lambda Calculus (0) | 2024.05.10 |
---|---|
8. Dependent Types and Pi Types (0) | 2024.05.10 |
6. Polymorphism and Parametric Polymorphism (0) | 2024.05.10 |
5. Type Safety: Progress and Preservation Theorems (0) | 2024.05.10 |
4. Introduction to Inference Rules and Typing Rules (0) | 2024.05.10 |