By default, all of the top-level bindings that you define in a module are exported and available to any code that imports your module. This is convenient since it means that we can start writing modules without needing to think about what should or shouldn’t be visible to consumers of our module, but frequently we’d like to have more control over what we choose to export. For example, we might want to hide some functions we’ve written that shouldn’t be part of our public API. Export lists are a way to get fine-grained control over what is, and isn’t, exported from the modules that you define. In this section, you’ll learn how to use export lists to control what is visible to consumers of your module, and work through several different use-cases where export lists can help you define a better API for your module.
Export Lists
Just like import lists, which let you choose what should be imported from a module, export lists let you choose what should be exported by your module. The syntax for an export list is similar to the syntax for an import list. To add an export list to your module, you need to add a comma-separated list of what you want to export. The export list should come after the module name before the where keyword. For example, let’s add a new value, testMessage , to our example module. We’ll also update our export list to specifically export testMessage :
| | {-# LANGUAGE RecordWildCards #-} |
| | module HaskellBook.Examples.Introduction.CreatingModules |
| | ( testMessage |
| | ) where |
| | |
| | data Name = Name { getName :: String } |
| | data Salutation = Salutation { getSalutation :: String } |
| | |
| | data GreetingMessage = GreetingMessage |
| | { greetingSalutation :: Salutation |
| | , greetingTo :: Name |
| | , greetingFrom :: [ Name ] |
| | } |
| | |
| | defaultMessage :: GreetingMessage |
| | defaultMessage = GreetingMessage |
| | { greetingSalutation = Salutation "Hello" |
| | , greetingTo = Name "Friend" |
| | , greetingFrom = [] |
| | } |
| | |
| | formatMessage :: GreetingMessage -> String |
| | formatMessage GreetingMessage {..} = |
| | greetingWithSuffix |
| | where |
| | basicGreeting = |
| | getSalutation greetingSalutation <> " " <> getName greetingTo |
| | |
| | greetingWithSuffix = |
| | case greetingFrom of |
| | [] -> |
| | basicGreeting <> "!" |
| | [friend] -> |
| | basicGreeting <> ", from: " <> getName friend |
| | [friendA, friendB] -> |
| | basicGreeting <> ", from: " <> |
| | getName friendA <> " and " <> getName friendB |
| | friends -> |
| | basicGreeting <> ", from your friends: " <> |
| | formatFriendList friends |
| | |
| | formatFriendList friends = |
| | case friends of |
| | [] -> |
| | "" |
| | [friend] -> |
| | "and " <> getName friend |
| | (friend:moreFriends) -> |
| | getName friend <> ", " <> formatFriendList moreFriends |
| | |
| | testMessage :: String |
| | testMessage = |
| | formatMessage $ defaultMessage { greetingFrom = [ Name "test example" ] } |
You’ll notice in this example that we’ve moved the export list down onto a separate line. This syntax is allowed for both import and export lists, but it’s more common with export lists, since they tend to be longer than import lists. With our export list in place, let’s run cabal repl again and import our module. When we do, you’ll see that while testMessage is available, nothing else that we’ve defined in our module is visible:
| | λ import HaskellBook.Examples.Introduction.CreatingModules |
| | λ putStrLn testMessage |
| | Hello Friend, from: test example |
| | λ defaultMessage |
| | |
| | <interactive>:3:1: error: Variable not in scope: defaultMessage |
| | λ :type formatMessage |
| | |
| | <interactive>:1:1: error: Variable not in scope: formatMessage |
When we add an export list, nothing is exported by default anymore. We need to add anything that we want to be available into the export list.
Although export lists can be a useful way of controlling what part of your code makes up the visible external API, we don’t necessarily want to give up the benefits of interactive development with ghci . You can comment out the export list while you’re in development, and then uncomment it when you’re done, but that’s not a particularly satisfying solution. Thankfully, if you open your code in ghci with :load rather than import , everything defined in the module will be available whether you included it in your export list or not. For example, if you :load your module without changing the export list, you’ll see that you can still reference everything in your module:
| | λ :load src/ HaskellBook / Examples / Introduction / CreatingModules .hs |
| | [1 of 1] Compiling HaskellBook . Examples . Introduction . CreatingModules ( |
| | src/ HaskellBook / Examples / Introduction / CreatingModules .hs, interpreted) |
| | Ok , one module loaded. |
| | λ :type default Message |
| | defaultMessage :: GreetingMessage |
| | λ :t Name |
| | Name :: String -> Name |
Dealing with Constructors and Field Selectors
Now that you know how to create an export list, let’s update our example to export the remaining parts of our module. Start by copying the example:
| | {-# LANGUAGE RecordWildCards #-} |
| | module HaskellBook.Examples.Introduction.CreatingModules |
| | ( Name |
| | , Salutation |
| | , GreetingMessage |
| | , defaultMessage |
| | , formatMessage |
| | , testMessage |
| | ) where |
| | |
| | data Name = Name { getName :: String } |
| | data Salutation = Salutation { getSalutation :: String } |
| | |
| | data GreetingMessage = GreetingMessage |
| | { greetingSalutation :: Salutation |
| | , greetingTo :: Name |
| | , greetingFrom :: [ Name ] |
| | } |
| | |
| | defaultMessage :: GreetingMessage |
| | defaultMessage = GreetingMessage |
| | { greetingSalutation = Salutation "Hello" |
| | , greetingTo = Name "Friend" |
| | , greetingFrom = [] |
| | } |
| | |
| | formatMessage :: GreetingMessage -> String |
| | formatMessage GreetingMessage {..} = |
| | greetingWithSuffix |
| | where |
| | basicGreeting = |
| | getSalutation greetingSalutation <> " " <> getName greetingTo |
| | |
| | greetingWithSuffix = |
| | case greetingFrom of |
| | [] -> |
| | basicGreeting <> "!" |
| | [friend] -> |
| | basicGreeting <> ", from: " <> getName friend |
| | [friendA, friendB] -> |
| | basicGreeting <> ", from: " <> |
| | getName friendA <> " and " <> getName friendB |
| | friends -> |
| | basicGreeting <> ", from your friends: " <> |
| | formatFriendList friends |
| | |
| | formatFriendList friends = |
| | case friends of |
| | [] -> |
| | "" |
| | [friend] -> |
| | "and " <> getName friend |
| | (friend:moreFriends) -> |
| | getName friend <> ", " <> formatFriendList moreFriends |
| | |
| | testMessage :: String |
| | testMessage = |
| | formatMessage $ defaultMessage { greetingFrom = [ Name "test example" ] } |
Now that we’ve expanded our export list, let’s load our program up again with cabal repl and try to generate a few messages. We’ll start with a default message:
| | λ import HaskellBook.Examples.Introduction.CreatingModules |
| | λ putStrLn $ formatMessage defaultMessage |
| | Hello Friend ! |
So far, so good! Next, let’s modify our default message:
| | λ putStrLn $ formatMessage $ |
| | defaultMessage {greetingTo = Name "Module Demo"} |
| | |
| | <interactive>:3:46: error: Not in scope: ‘greetingTo’ |
Unfortunately, we can’t use our API as designed with our current export list. Although we exported our GreetingMessage type, that doesn’t seem to have extended to exporting the field selectors that were created when we defined the record. We can go back and update our export list momentarily, but for now we ought to be able to create a GreetingMessage without referencing the record fields. Let’s try that to see if we can still create a custom message:
| | λ msg = GreetingMessage ( Salutation "Hello" ) ( Name "Module Demo" ) [] |
Unfortunately, it turns out that we can’t create a message this way either. Depending on the version of GHC that you are using, you might see different error messages. In GHC 9.2, you will see this error:
| | <interactive>:5:7: error: |
| | • Illegal term-level use of the type constructor ‘GreetingMessage’ |
| | imported from ‘HaskellBook.Examples.Introduction.CreatingModules’ |
| | (and originally defined |
| | at src/HaskellBook/Examples/Introduction/CreatingModules.hs:(14,1)-(18,3)) |
| | • In the expression: |
| | GreetingMessage (Salutation "Hello") (Name "Module Demo") [] |
| | |
| | In an equation for ‘msg’: |
| | msg = GreetingMessage (Salutation "Hello") (Name "Module Demo") [] |
In GHC 8.10, the error message will look a little different:
| | <interactive>:2:7: error: |
| | Data constructor not in scope: |
| | GreetingMessage :: t0 -> t1 -> [a0] -> t |
| | |
| | <interactive>:2:24: error: |
| | Data constructor not in scope: Salutation :: t2 -> t0 |
| | |
| | <interactive>:2:45: error: |
| | Data constructor not in scope: Name :: t3 -> t1 |
In both cases, the error is caused by the same underlying issue: we’ve exported the types for Name , Salutation , and GreetingMessage but we haven’t exported their constructors , or any field selectors.
You can export field constructors just like any other function. In this case, we could add greetingSalutation , greetingTo , and greetingFrom to our export list, but we still wouldn’t be able to create a GreetingMessage value. To update the values in defaultMessage we need to provide either Name or Salutation values, and creating those means we need to call the Name or Salutation constructors. If we want to export a value constructor for our types, we need to include those alongside the types that we’re exporting. The syntax for this looks like an export list within an export list. We add a comma-separated list of all of the constructors that we want to export for a particular type. In our case, we only have a single value constructor for each of these types. Let’s go ahead and add the value constructors for all of our types. Our export list will look like this:
| | module HaskellBook.Examples.Introduction.CreatingModules |
| | ( Name ( Name ) |
| | , Salutation ( Salutation ) |
| | , GreetingMessage ( GreetingMessage ) |
| | , greetingSalutation |
| | , greetingTo |
| | , greetingFrom |
| | , defaultMessage |
| | , formatMessage |
| | , testMessage |
| | ) where |
With the field selectors and constructors added to the export list, you can freely create new message values now:
| | λ putStrLn . formatMessage $ |
| | defaultMessage { greetingTo = Name "Module Demo" } |
| | Hello Module Demo ! |
You can also include any field selectors in the export list for a particular type. Let’s update our export list again to include the field selectors for each of our types in their respective export lists:
| | module HaskellBook.Examples.Introduction.CreatingModules |
| | ( Name ( Name , getName ) |
| | , Salutation ( Salutation , getSalutation ) |
| | , GreetingMessage ( GreetingMessage |
| | , greetingSalutation |
| | , greetingTo |
| | , greetingFrom |
| | ) |
| | , defaultMessage |
| | , formatMessage |
| | , testMessage |
| | ) where |
For types with many constructors, or large records, it can be inconvenient to type out everything that you might want to export for a type. Even for types with only a single constructor and a small number of field selectors you might not want to update the export list every time you make a change for the type. To help with that, there’s a special syntax that you can use to export all of the constructors and field selectors associated with a particular type. Let’s update our export list so we can see an example:
| | module HaskellBook.Examples.Introduction.CreatingModules |
| | ( Name (..) |
| | , Salutation (..) |
| | , GreetingMessage (..) |
| | , defaultMessage |
| | , formatMessage |
| | , testMessage |
| | ) where |
You can use the same syntax for importing types, constructors, and field selectors. Let’s open up a fresh ghci session with cabal repl and try out a few more imports using this current version of our module. We’ll start by importing the Name type and its constructor, but not the getName field selector:
| | λ exampleName = Name "haskeller" |
| | λ getName exampleName |
| | |
| | <interactive>:5:1: error: |
| | Variable not in scope: getName :: Name -> t |
Smart Constructors
It might seem inconvenient to need to export constructors and field selectors explicitly when you export the types you’ve defined in a module, but being able to keep these internal to a module is an important part of a common pattern you’ll see in Haskell applications: smart constructors . A smart constructor is an ordinary function that lets you construct a value. Unlike a standard value constructor, smart constructors can include some additional logic. One of the most common ways to use a smart constructor is to perform some additional validation before creating a value. When you export a smart constructor for a type, but don’t export the actual constructor, then you can guarantee that the only way a user could have gotten a value for your type is having gone through the smart constructor. This lets you make simplifying assumptions throughout the rest of your code by performing your basic validation once, at the time that you’d be creating the value.
Let’s look at this in practice with a small example. Imagine that we are writing a program that needs to deal with a list of numbers, and we regularly want to find the smallest element in the list. We could use the minimum function in Prelude , but that’s a partial function that will fail if we call it with an empty list. Since it needs to work with any list, it also has to go through the entire list to make sure it’s found the smallest element.
In our program, we can write a much better minimum function if we can be sure that we’re always working with a list that has at least one element, and if we always know the list we’re working with will be sorted. To do that, let’s add a new module to our project called HaskellBook.Examples.SortedList . We’ll import the sort function from Data.List and we’ll hide the minimum function from Prelude since we want to define our own:
| | module HaskellBook.Examples.SortedList where |
| | |
| | import Data.List ( sort ) |
| | import Prelude hiding ( minimum ) |
Now, let’s define a new SortedList type. Rather than re-inventing the list type from scratch, we’ll define our sorted list in terms of the standard list type:
| | data SortedList = SortedList { getSorted :: [ Int ] } |
Finally, we can write a minimum function that takes advantage of the fact that we know we’re dealing with non-empty sorted lists:
| | minimum :: SortedList -> Int |
| | minimum ( SortedList numbers) = head numbers |
You might have already spotted the problem, but let’s use cabal repl to load this module into ghci and test it out:
| | λ import qualified HaskellBook.Examples.SortedList as SortedList |
| | λ SortedList .minimum $ SortedList . SortedList [1,2,5,10] |
So far, so good. Unfortunately, the assumptions that we’re making about our list being non-empty and sorted aren’t being enforced right now, so we’re entirely free to pass in bad data:
| | λ SortedList .minimum $ SortedList . SortedList [] |
| | *** Exception : Prelude .head: empty list |
| | λ SortedList .minimum $ SortedList . SortedList [10,9..] |
| | 10 |
The problem is that we’re allowing ourselves to create a SortedList with any list we want, sorted or not, and we’re not doing anything to validate that the list is well formed. We can fix this with a smart constructor and an export list. We’ll start by creating a smart constructor called makeSortedList :
| | makeSortedList :: [ Int ] -> Maybe SortedList |
| | makeSortedList [] = Nothing |
| | makeSortedList numbers = Just $ SortedList (sort numbers) |
Our smart constructor takes a list in and tries to generate a sorted non-empty list. If we get a non-empty list, we can do that by sorting whatever the user gives us. If they give us an empty list, we can’t do anything with it, so we have to return Nothing . This might seem like it’s a less convenient API, since the user now has to deal with a Maybe value whenever they want to construct a SortedList , but it allows us to handle all of the validation once when the list is initially created. This simplifies the rest of our code, and it also pushes the error handling up to the user at the time that they are creating the value in the first place, and are most likely to be able to make a sensible decision about what to do next when faced with an error.
Let’s take another look at our module, this time with our export list in place:
| | module HaskellBook.Examples.SortedList |
| | ( SortedList ( getSorted ) |
| | , makeSortedList |
| | , minimum |
| | ) where |
| | |
| | import Data.List ( sort ) |
| | import Prelude hiding ( minimum ) |
| | |
| | data SortedList = SortedList { getSorted :: [ Int ] } |
| | |
| | makeSortedList :: [ Int ] -> Maybe SortedList |
| | makeSortedList [] = Nothing |
| | makeSortedList numbers = Just $ SortedList (sort numbers) |
| | |
| | minimum :: SortedList -> Int |
| | minimum ( SortedList numbers) = head numbers |
As you can see, with our smart constructor in place, the only way the user will have to create a SortedList value is by going through our makeSortedList function. This lets us ensure that we’re always working with valid data.
Phantom Types and Export Lists
Before we move on from export lists, let’s look at another example of how we can use export lists to create a safer interface into our code. This time, we’ll build a small model of an API that you might use to manage user profile information for a social media application.
Let’s start with a straightforward implementation of our API. We’ll enable the RecordWildCards extension now, since we’ll be using it later on in this section:
| | {-# LANGUAGE RecordWildCards #-} |
| | |
| | module HaskellBook.Examples.UserInfo |
| | ( User |
| | , lookupUser |
| | , getUserName |
| | , getUserScore |
| | , getUserEmailAddress |
| | ) where |
| | import Data.List ( find ) |
| | |
| | data User = User |
| | { userName :: String |
| | , userInternetPoints :: Int |
| | , userPassword :: String |
| | , userEmailAddress :: String |
| | } |
| | |
| | users :: [ User ] |
| | users = [george, porter] |
| | where |
| | george = User |
| | { userName = "george" |
| | , userInternetPoints = 1000 |
| | , userPassword = "secret" |
| | , userEmailAddress = "[email protected]" |
| | } |
| | porter = User |
| | { userName = "porter" |
| | , userInternetPoints = 500 |
| | , userPassword = "hunter2" |
| | , userEmailAddress = "[email protected]" |
| | } |
| | |
| | lookupUser :: String -> Maybe User |
| | lookupUser name = |
| | find ( \ user -> userName user == name) users |
| | |
| | getUserName :: User -> String |
| | getUserName = userName |
| | |
| | getUserScore :: User -> Int |
| | getUserScore = userInternetPoints |
| | |
| | getUserEmailAddress :: User -> String |
| | getUserEmailAddress = userEmailAddress |
In this example, we’ve defined a very small user query API. Given a username, we can look for the user in a hardcoded list. Once we have a user, we can get some information about them, like their username, how many internet points they’ve earned, and their email address. Since we’re not exporting the User constructor, or the userPassword field selector, we’ve also made use of our export list to ensure we can’t accidentally leak password information outside of the module. Of course, in a real-world application we’d want to avoid storing passwords in plain text altogether, but we’ll stick with it to simplify our example.
One problem we have with the API for our application is it treats all user data equally. Although usernames and internet point counts are public information that should be available to anyone, a user’s email address is private and we shouldn’t display it to anyone except for the user themselves, after they’ve logged in. It turns out that we can use export lists to help us build an API that enforces this. Let’s refactor our example so that we can see how this works.
First, we need a way to keep track of whether a user has been authenticated or not. We’ll add two types to keep track of this information. We’re only going to track whether a user has been authenticated or not at the type level, so we don’t need to add a value constructor for our types:
| | data Authenticated |
| | data Unauthenticated |
Importantly, we’re not going to add either of these types to our export list. We want to keep these two types entirely internal to our module.
Next, we’d like to keep track of whether a particular user is authenticated or not. We’ll do that by adding a new type parameter to User . We’re not going to have any values of this type, we’re just using it keep track of whether a particular value has been authenticated or not. We call these types that don’t have any corresponding values phantom types :
| | data User isAuthenticated = User |
| | { userName :: String |
| | , userInternetPoints :: Int |
| | , userPassword :: String |
| | , userEmailAddress :: String |
| | } |
Now we can update the types of our functions. For example, when we first look up a user by name, we want the user to be unauthenticated until they log in:
| | lookupUser :: String -> Maybe ( User Unauthenticated ) |
| | lookupUser name = |
| | find ( \ user -> userName user == name) users |
We should be able to get a user’s username or score regardless of whether they are logged in or not, so we’ll make the type parameter polymorphic for those functions:
| | getUserName :: User isAuthenticated -> String |
| | getUserName = userName |
| | |
| | getUserScore :: User isAuthenticated -> Int |
| | getUserScore = userInternetPoints |
Finally, getting a user’s email address should only work if they are authenticated:
| | getUserEmailAddress :: User Authenticated -> String |
| | getUserEmailAddress = userEmailAddress |
You’ll notice that we didn’t have to change the implementation of any of our functions, only their types. Our phantom type only exists as the type level, so there’s nothing that we need to do at the value level to restrict when we can call a function. Even though we haven’t changed anything at the value level, we can load our code up into ghci with cabal repl and see that it’s working as intended. We can look up a user and get their name and score:
| | λ import HaskellBook.Examples.UserInfo |
| | λ ( Just george) = lookupUser "george" |
| | λ getUserName george |
| | "george" |
| | λ getUserScore george |
| | 1000 |
If we try to get an email address from our unauthenticated user, we’ll get a type error:
| | λ getUserEmailAddress george |
| | |
| | <interactive>:5:21: error: |
| | • Couldn't match type ‘HaskellBook.Examples.UserInfo.Unauthenticated’ |
| | with ‘HaskellBook.Examples.UserInfo.Authenticated’ |
| | Expected type: User HaskellBook.Examples.UserInfo.Authenticated |
| | Actual type: User HaskellBook.Examples.UserInfo.Unauthenticated |
| | • In the first argument of ‘getUserEmailAddress’, namely ‘george’ |
| | In the expression: getUserEmailAddress george |
| | In an equation for ‘it’: it = getUserEmailAddress george |
If we want to be able to get access to a user’s email, we will need a way to authenticate them.
Let’s add an authenticate function that will return an authenticated user if given a correct password:
| | authenticate :: User Unauthenticated -> String -> Maybe ( User Authenticated ) |
| | authenticate User {..} password |
| | | userPassword == password = Just User {..} |
| | | otherwise = Nothing |
You’ll notice in this example that we’re finally making use of the RecordWildCards extension. First, we get all of the fields out of the unauthenticated User value that’s been passed into our function. If the password matches the one that we’re trying to authenticate with, we construct a new User value, this time one that’s been authenticated. We need to construct a new User value here since the newly constructed value has a different type from the one that was passed in, which was unauthenticated.
Like with our earlier sorted list example, our authentication API puts the burden of error handling on the user by returning a Maybe handle, but it simplifies the rest of our code by letting us assume that no authenticated users can exist unless they’ve successfully passed through the authentication step.
Now that we’ve implemented authentication, let’s take a look at the final version of our code:
| | {-# LANGUAGE RecordWildCards #-} |
| | module HaskellBook.Examples.UserInfo |
| | ( User |
| | , lookupUser |
| | , authenticate |
| | , getUserName |
| | , getUserScore |
| | , getUserEmailAddress |
| | ) where |
| | import Data.List ( find ) |
| | |
| | data Authenticated |
| | data Unauthenticated |
| | |
| | data User isAuthenticated = User |
| | { userName :: String |
| | , userInternetPoints :: Int |
| | , userPassword :: String |
| | , userEmailAddress :: String |
| | } |
| | users :: [ User a] |
| | users = [george, porter] |
| | where |
| | george = User |
| | { userName = "george" |
| | , userInternetPoints = 1000 |
| | , userPassword = "secret" |
| | , userEmailAddress = "[email protected]" |
| | } |
| | porter = User |
| | { userName = "porter" |
| | , userInternetPoints = 500 |
| | , userPassword = "hunter2" |
| | , userEmailAddress = "[email protected]" |
| | } |
| | |
| | lookupUser :: String -> Maybe ( User Unauthenticated ) |
| | lookupUser name = |
| | find ( \ user -> userName user == name) users |
| | |
| | authenticate :: User Unauthenticated -> String -> Maybe ( User Authenticated ) |
| | authenticate User {..} password |
| | | userPassword == password = Just User {..} |
| | | otherwise = Nothing |
| | |
| | getUserName :: User isAuthenticated -> String |
| | getUserName = userName |
| | |
| | getUserScore :: User isAuthenticated -> Int |
| | getUserScore = userInternetPoints |
| | |
| | getUserEmailAddress :: User Authenticated -> String |
| | getUserEmailAddress = userEmailAddress |
By carefully choosing what we want to export from our module, and adding some additional information at the type level that is only accessible from within our module, we’ve been able to enforce an authentication policy at the type level using phantom types. Now, any user who chooses to write code against our API will get a type error if they write code that might accidentally leak private information to an unauthenticated user. In this way, we’ve used Haskell’s type system and modules to improve the security of our application at compile time. This is an example of a larger pattern that you’ll see used in some Haskell applications where “resources” of various sorts are locked away behind smart constructors and unexported types. It can sometimes be challenging to figure out how to approach designing APIs this way, and not every problem lends itself to this type of solution, but when you have the opportunity, it can be a highly effective way of building APIs that are safe by default.
Re-Exporting Code from Other Modules
So far we’ve looked at examples of how to export code defined in a module from that module. We’re not limited to only exporting things where they are defined though. A module can export anything from a module that’s in scope, including code we’ve imported from other modules. As an example, let’s build a demo of some of the things we’ve built while working on this section.
We’ll start by making it easier to import all of the examples that we’ve built. A common pattern that you’ll see in Haskell codebases is that there will be several small independent modules that exist at some point in the module hierarchy, along with a parent module that re-exports all, or the most relevant parts, of those modules. We can see this in action by creating our own Examples module that will re-export some of our code from the various modules we’ve already defined.
Create a new module named HaskellBook.Examples at src/HaskellBook/Examples.hs :
| | module HaskellBook.Examples where |
We won’t define any new functions in this module to keep the example small, although in real-world codebases you’ll sometimes see these parent modules include helper functions that are either useful across all of the modules that they re-export, or help ease interoperability between the modules. We’ll just focus on re-exporting code from our example modules. Let’s start with UserInfo .
Our UserInfo module is fairly large, and has quite a bit of code and it would be nice to make all of it available for our demo. We can do that by re-exporting the entire module. In order to re-export a module, we can list it, along with the module keyword in our export list. We can only export code that’s in scope in our module, so we’ll also need to import the module:
| | module HaskellBook.Examples |
| | ( module HaskellBook . Examples . UserInfo |
| | ) |
| | where |
| | |
| | import HaskellBook.Examples.UserInfo |
Next, let’s look back at our original module, HaskellBook.Examples.Introduction.CreatingModules . It’s a very long module name to type out repeatedly, so let’s import it with a local alias. While we’re at it, the testMessage we’re exporting from that module isn’t very interesting for demo purposes, so let’s hide it from our import:
| | module HaskellBook.Examples |
| | ( module HaskellBook . Examples . UserInfo |
| | , module CreatingModules |
| | ) |
| | where |
| | |
| | import HaskellBook.Examples.UserInfo |
| | import HaskellBook.Examples.Introduction.CreatingModules |
| | as CreatingModules hiding (testMessage) |
In this example, you can see that when we re-export a module that we’ve imported using a local alias, we also use the local alias to refer to it when we re-export it. You’ll also notice that we’ve broken up the import statement onto two lines. You can break up import statements into as many lines as you like, so long as you indent all of the additional lines with at least one space.
Finally, let’s add an import for SortedList . As you may recall from when we originally wrote SortedList , it exports its own version of the minimum function that conflicts with the version defined in Prelude . To help avoid any potential name conflicts, let’s import SortedList both qualified and with a local alias:
| | import qualified HaskellBook.Examples.SortedList as SortedList |
Unfortunately, since we’ve used a qualified import we can’t directly export the entire module. When you use a qualified import of a module, you’ll need to explicitly list everything from that module you want to export in your export list:
| | module HaskellBook.Examples |
| | ( module HaskellBook . Examples . UserInfo |
| | , module CreatingModules |
| | , SortedList . SortedList (..) |
| | , SortedList . makeSortedList |
| | , SortedList . minimum |
| | ) where |
| | |
| | import HaskellBook.Examples.UserInfo |
| | import HaskellBook.Examples.Introduction.CreatingModules |
| | as CreatingModules hiding (testMessage) |
| | import qualified HaskellBook.Examples.SortedList as SortedList |
Now that we’ve create a module that exports everything we might want to use, we can build a demo. Let’s create a new module named ModuleDemo :
| | module ModuleDemo where |
| | import qualified HaskellBook.Examples as Examples |
| | |
| | georgesEmailAddress :: Maybe String |
| | georgesEmailAddress = |
| | case Examples .lookupUser "george" of |
| | Nothing -> |
| | Nothing |
| | Just unathenticatedGeorge -> |
| | case Examples .authenticate unathenticatedGeorge "secret" of |
| | Nothing -> Nothing |
| | Just george -> |
| | Just $ Examples .getUserEmailAddress george |
| | |
| | friendlyEmail :: String -> String |
| | friendlyEmail emailAddress = |
| | Examples .formatMessage Examples . GreetingMessage |
| | { Examples .greetingSalutation = Examples . Salutation "Hello" |
| | , Examples .greetingTo = Examples . Name emailAddress |
| | , Examples .greetingFrom = [ Examples . Name "mailer daemon" ] |
| | } |
| | |
| | demo :: String |
| | demo = |
| | maybe "unknown user" friendlyEmail georgesEmailAddress |
As you can see from our demo example, when we are importing a module we do not need to be concerned with whether something that’s exported by the module was defined in that module, or was re-exported from a different module. This makes re-exports a useful tool for refactoring, since we can change where things are defined while maintaining a compatible API at the module level.