Google News
logo
Haskell - Interview Questions
List the types of polymorphism in Haskell?
In Haskell, there are two main types of polymorphism : parametric polymorphism (also known as generics) and ad-hoc polymorphism (also known as overloading).

These polymorphic features allow you to write code that can work with a range of types, providing flexibility and code reuse.

1. Parametric Polymorphism (Generics) :
   * Parametric polymorphism allows you to write functions or data types that can operate uniformly on different types without specifying the concrete types in advance.
   * In Haskell, parametric polymorphism is achieved through type variables, which represent placeholders for any type. These type variables are universally quantified, meaning they can be instantiated with any type when the function is used.
   * Functions that use parametric polymorphism are often referred to as generic functions or polymorphic functions.
   * Examples of parametric polymorphism in Haskell include the `id` function, which has the type `a -> a`, meaning it works for any type `a`, and the list type `[]`, which can hold elements of any type.
2. Ad-hoc Polymorphism (Overloading) :
   * Ad-hoc polymorphism allows you to define functions or operators that can have different implementations depending on the types of their arguments.
   * In Haskell, ad-hoc polymorphism is achieved through type classes, which define a set of operations or behaviors that a type must support.
   * Type classes provide a way to define overloaded functions that can have multiple implementations, each specific to a particular type or set of types that satisfy the type class constraints.
   * Examples of ad-hoc polymorphism in Haskell include the `Eq` type class, which provides equality comparison (`==`) and inequality comparison (`/=`) operations, and the `Ord` type class, which provides ordering operations (`<`, `>`, `<=`, `>=`).
Advertisement