strangerRidingCaml

6. Polymorphism and Parametric Polymorphism 본문

Type theory

6. Polymorphism and Parametric Polymorphism

woddlwoddl 2024. 5. 10. 02:32
728x90
Polymorphism and Parametric Polymorphism

Polymorphism and Parametric Polymorphism

Polymorphism is a programming language feature that allows a single function or data type to operate on different types.

There are two main types of polymorphism: ad-hoc polymorphism and parametric polymorphism.

Ad-hoc polymorphism, also known as overloading, refers to the ability to define multiple functions or methods with the same name but different implementations based on the types of their arguments.

Parametric polymorphism, on the other hand, allows a function or data type to be written generically, so that it can operate uniformly on data of any type.

In parametric polymorphism, the same code can be used with different types without modification.

One common example of parametric polymorphism is the use of generic types in languages like Java and C++.

For instance, in Java, you can define a generic class or method using type parameters, allowing it to work with different types.

Lab Activity: Implementing Parametric Polymorphism

Let's implement a simple generic function in Python to demonstrate parametric polymorphism.


def print_list(lst):
    for item in lst:
        print(item)

def main():
    int_list = [1, 2, 3, 4, 5]
    str_list = ["apple", "banana", "cherry"]
    
    print("Printing integer list:")
    print_list(int_list)
    
    print("Printing string list:")
    print_list(str_list)

if __name__ == "__main__":
    main()
  

In the lab activity, we define a `print_list` function that can print elements of any list, irrespective of their type.

We demonstrate the parametric polymorphism by calling the `print_list` function with both integer and string lists.