Skip to content

Module Aliases

When using fully qualified function names, writing the full module name becomes tedious quickly. When importing modules, we can introduce aliases for modules, and use these aliases to qualify functions imported from these modules. For example, when working with arrays, the import statements I tend to use are

import           Data.Array (Array)
import qualified Data.Array as A

The as A part introduces A as an alias for Data.Array. With these two imports, I can use the Array type unqualified in type signatures, and I can call, for example, the map function for arrays as A.map.

It is even possible to use the same alias for multiple imported modules. This works without problems as long as we do not import two functions with the same name from different modules. For example,

import qualified Data.List  as X
import qualified Data.Array as X

would in itself not create any problems, but calling X.map would because the compiler cannot tell whether X.map refers to the function from Data.List or to the one from Data.Array. This is the same problem as when trying to call map after importing Data.Array unqualified.

An example where using the same alias for multiple module is useful is

import qualified Data.Text    as T
import qualified Data.Text.IO as T

The Data.Text module provides the Text data type that represents text more space-efficiently than standard Strings, along with functions to manipulate Text. The Data.Text.IO module provides counterparts to the standard I/O functions defined in System.IO, only these functions now read and write Text, not Strings. Data.Text and Data.Text.IO do not export any functions with the same name. By importing both modules with the alias T, we can use T. as the prefix for all functions that work with Text, whether they are I/O functions or pure functions to manipulate Text.

Once again, aliases introduced using the as keyword can be used in combination with import lists, and aliases can be used whether a module is imported qualified or not. The most common use is to use them with qualified imports that don't have an explicit import list.