WalzoneInterview Prep
📞 Interviewing soon? Practice with a realistic AI mock phone interview — it calls you, then scores you. First 15 min FREE →

Haskell · Expert · question 65 of 100

What is the role of "Existential Quantification" in Haskell?

📕 Buy this interview preparation book: 100 Haskell questions & answers — PDF + EPUB for $5

Existential Quantification in Haskell is a type system feature that allows expressing data types with components of unknown or hidden types. Existential types provide a way to hide the concrete type of a value behind a typeclass constraint, enabling an increased level of abstraction and modularity.

The main idea behind existential types is that they encapsulate a value and its typeclass implementation, allowing you to use this value only through the interface provided by the typeclass without knowing the actual concrete type of the value.

In Haskell, existential types are generally introduced using the ‘data‘ or ‘newtype‘ keyword, accompanied by the ‘forall‘ keyword from the ‘ExistentialQuantification‘ language extension. Let’s see an example of an existential type:

{-# LANGUAGE ExistentialQuantification #-}

import Data.Typeable

data ShowBox = forall a. Show a => ShowBox a

instance Show ShowBox where
    show (ShowBox a) = show a

In this example, ‘ShowBox‘ is an existential type that can hold any value that has an instance of the ‘Show‘ typeclass. When pattern matching on a ‘ShowBox‘ constructor, we are able to call the ‘show‘ function on the value inside, even though we don’t know its concrete type.

You can use existential types to define heterogeneous collections, in which you can store different types of values as long as they adhere to a certain interface (in this case, the ‘Show‘ typeclass). Let’s use ‘ShowBox‘ to create a heterogeneous list:

exampleList :: [ShowBox]
exampleList = [ShowBox (5 :: Int), ShowBox "hello", ShowBox (3.14 :: Double)]

Here, ‘exampleList‘ is a heterogeneous list containing values of different types, all wrapped in the ‘ShowBox‘ existential type. We can now process this list without knowing the concrete type of each element:

showAll :: [ShowBox] -> [String]
showAll xs = map show xs

In summary, Existential Quantification in Haskell allows creating data types in which an unknown or hidden type is constrained by one or more typeclasses. They enable abstraction and heterogeneous collections with a shared interface, and can lead to more modular design.

Reading is step one. Saying it out loud is the interview. Our AI interviewer calls your phone and runs a realistic Haskell interview — then scores it.
📞 Practice Haskell — free 15 min
📕 Buy this interview preparation book: 100 Haskell questions & answers — PDF + EPUB for $5

All 100 Haskell questions · All topics