Today I Learned

Some of the things I've learned every day since Oct 10, 2016

210: Type Variables (Haskell)

In Haskell, type variables are roughly the equivalent of generics in languages like Java. They enable a function to operate on and return different types, so long as the function doesn’t depend on any specific behavior of the types involved. (These are called polymorphic functions.)

For instance, if in GHCI we use :t head to examine the type of the head function which returns the first element of a list, we see it has the type head :: [a] -> a. a is a type variable, meaning it could be any type. This just means head takes a list with elements of any type a and returns a single element of that same type.

As another example, :t fst gives fst :: (a, b) -> a. Since pairs in Haskell aren’t homogenous, it’s possible that a pair’s first and second elements have different types a and b respectively (although they could be the same). fst just returns a single element of type a.


Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

%d bloggers like this: