Importing modules defined by libraries is a great starting point when you are building an application, but as your programs start to grow larger, you’ll also quickly realize that you’ll need to use them in your own application to help you organize and re-use your own code. Modules are the basic unit of organization in Haskell applications, and in this section, you’ll learn how to write modules, control what they export, and how to design an application to make the best use of modules so that your code is easy to use and re-use.
Let’s start by looking at how we can create a module. Haskell modules are closely related to individual source files. Each file contains one module, and each module is defined by a single file. Generally, the name of the file that defines a module should match the name of the module itself. For example, if you have a module named Example , it should be defined in a file named Example.hs . Modules exist in a hierarchy that mirrors the organization of your source files. If you have a directory named Examples and that directory contains a file named ExampleOne.hs then the module defined in that file should be named Examples.ExampleOne . Each subdirectory adds a new section to the module name.
The relationship between file path and module name should be relative to the source directory for your application. For example, if you have a new application called HaskellBook and you’ve set the source directory for the project to src , then a file at the path src/HaskellBook/Examples/Introduction/CreatingModules.hs should define a module named HaskellBook.Examples.Introduction.CreatingModules . The src is omitted because that’s the root source code directory for the project.
To get a first-hand feel for how we can use modules to organize our code, let’s use cabal-init to create a new cabal project called module-examples . We’ll make it a library, and set the source directory to src .
Once you’ve created the project, we’ll add our first new module. Create a new file at src/HaskellBook/Examples/Introduction/CreatingModules.hs . You’ll need to create all of the intermediate subdirectories as well. Inside of the file, add a new module header. We’ll name the module HaskellBooks.Examples.Introduction.CreatingModules :
| | module HaskellBook.Examples.Introduction.CreatingModules where |
The syntax for creating a module should look familiar. We’ve been using the module and where keywords to define module headers since the beginning of the book. You’ve also seen the hierarchical naming module convention a couple of times when you’ve imported libraries as part of some of the examples in the book. This is, however, the first time that we’ve created a module with a longer name like this. You’ve likely noticed that the path to the file we created matches the name of the module. Each directory in the path to the file became a segment of the module name, separated by dots ( . ). This is the standard way for organizing source files and modules names in Haskell projects. These conventions aren’t strictly required. You can name your files and modules whatever you like, but most developers and most Haskell tooling will assume you’re following the standard naming conventions.
Now that we have a module to work with, we should also add it to our cabal file. You learned earlier that the cabal files give us two ways to add modules: we can add our new module to the exposed-modules section of the cabal file to make it available to any consumers of our library, or we can add it to the other-modules section if we want our new module to only be used internally within our library. For now, let’s add our new module to the exposed-modules section of the cabal file:
| | cabal-version: 2.4 |
| | name: module-examples |
| | version: 0.1.0.0 |
| | license: NONE |
| | extra-source-files: CHANGELOG.md |
| | |
| | library |
| | exposed-modules: MyLib |
| | , HaskellBook.Examples.Introduction.CreatingModules |
| | build-depends: base ^>=4.16.0.0 |
| | hs-source-dirs: src |
| | default-language: Haskell2010 |
Note that, depending on the version of cabal that you used to create the project, and the options you selected, your cabal file might look slightly different from the example.
Making Code Available for Re-Use
Now that we have a module, let’s add some code to it. By default, everything we define at the top level of our module will be exported. As an example, let’s add a function that will add some excitement to a message:
| | module HaskellBook.Examples.Introduction.CreatingModules where |
| | |
| | excitingMessage :: String -> String |
| | excitingMessage message = |
| | "Exciting news: " <> message <> "!!!" |
Now let’s load our library up into ghci . Since we want to load modules from the library that we’re writing, we’ll use cabal repl to start our ghci session instead of calling ghci directly. This will start up ghci with our library loaded, alongside any other dependencies we’ve added to our cabal file:
| | user@host$ cabal repl |
Although our library will be loaded in ghci , we’ll still need to import the modules we want to use. If you try to call excitingMessage without importing the module that defines it, we’ll get an error:
| | λ excitingMessage "Modularity" |
| | |
| | <interactive>:1:1: error: |
| | Variable not in scope: excitingMessage :: t0 -> t |
We can import our new module, which will make our function available:
| | λ import HaskellBook.Examples.Introduction.CreatingModules |
| | λ excitingMessage "Modularity" |
| | "Exciting news: Modularity!!!" |
Functions aren’t the only thing that get exported from a module. In the last section, you saw an example of how the Text type was exported by the Data.Text module. By default, any top-level functions, variables, and types will exported. To help illustrate this, let’s expand our example module by building a small library to let us create greeting messages.
We want our library to format greetings that include some particular salutation, for example, “hello” or “happy birthday.” The message will be to someone, and it might be from one or several people. Both the salutation and the names of the people in the message will be String data, but we don’t want to confuse a name for a salutation, so let’s start by creating pair of types so that we can keep the names and salutations separate:
| | data Name = Name { getName :: String } |
| | data Salutation = Salutation { getSalutation :: String } |
Next, let’s create a new record that holds all of the information about a greeting. We’ll call it GreetingMessage :
| | data GreetingMessage = GreetingMessage |
| | { greetingSalutation :: Salutation |
| | , greetingTo :: Name |
| | , greetingFrom :: [ Name ] |
| | } |
We can make our library more convenient for our users by providing a default greeting. If our users only want to change part of the default message, they can use record update syntax to change the fields they want to modify. Since our message only has three fields, this pattern won’t be as useful as it would be with larger records, especially records with more sensible defaults, but it’ll still serve as a good example of creating default values when we’re writing Haskell libraries:
| | defaultMessage :: GreetingMessage |
| | defaultMessage = GreetingMessage |
| | { greetingSalutation = Salutation "Hello" |
| | , greetingTo = Name "Friend" |
| | , greetingFrom = [] |
| | } |
Finally, let’s add a function to turn our GreetingMessage into a message we can print on the screen. You’re welcome to pick your own message formatting as you follow along with the example:
| | formatMessage :: GreetingMessage -> String |
| | formatMessage ( GreetingMessage greetingSalutation greetingTo greetingFrom) = |
| | 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 |
In this example, we’ve used pattern matching to extract all the fields of our GreetingMessage record. Let’s do a small refactor to make use of the RecordWildCards extension. Once you’ve done that, the final version of your greeting module should look like the example:
| | {-# LANGUAGE RecordWildCards #-} |
| | module HaskellBook.Examples.Introduction.CreatingModules 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 |
Now that we’ve turned our module into a small library, let’s load it back up into ghci with cabal repl so that we can see what is available to us when we import it. We’ll start by formatting the default message:
| | λ import HaskellBook.Examples.Introduction.CreatingModules |
| | λ formatMessage defaultMessage |
| | "Hello Friend!" |
As you would expect, both formatMessage and defaultMessage are available now that we’ve imported our library. What if we wanted to customize the message?
| | λ george = Name "George" |
| | λ remi = Name "Remi" |
| | λ porter = Name "Porter" |
| | λ formatMessage $ defaultMessage {greetingFrom = [george, remi, porter]} |
| | "Hello Friend, from your friends: George, Remi, and Porter" |
We can use record update syntax, so it would appear that the field selectors for GreetingMessage have been exported, along with the type constructor for Name . In fact, all the top-level functions and variables we’ve defined in our module are available. So are the types we’ve defined, along with their field selectors and constructors.
Types and values that we define in our module are available when we import it, but language extensions that we’ve enabled in a module are not carried over. We can see this for ourselves if we try to write a function that depends on the RecordWildCards extension. For example, let’s try to write a function that counts the number of people who sent a message:
| | λ import HaskellBook.Examples.Introduction.CreatingModules |
| | λ countSenders GreetingMessage{..} = length greetingFrom |
| | |
| | <interactive>:2:14: error: |
| | Illegal `..' in record pattern |
| | Use RecordWildCards to permit this |
Even though the extension was enabled in our module, we can’t use it outside of the module unless we enable the extension where we want to use it:
| | λ :set - XRecordWildCards |
| | λ countSenders GreetingMessage {..} = length greetingFrom |
| | λ countSenders defaultMessage |
| | 0 |
There are benefits and drawbacks to the fact that language extensions are only enabled in the module where they are defined. A benefit is that you can choose what extensions you want to enable on a case-by-case basis without requiring that users of your module make the same choice. On the other hand, a major drawback is that you may find yourself repeatedly adding the same handful of extensions across all, or most, of your modules. If you notice that you are enabling the same extensions in most modules, you might want to consider adding them to the default-extensions section in your cabal project. Let’s add RecordWildCards as a default extension for our library:
| | cabal-version: 2.4 |
| | name: module -examples |
| | version: 0.1.0.0 |
| | license: NONE |
| | extra-source-files: CHANGELOG .md |
| | |
| | library |
| | exposed-modules: MyLib |
| | , HaskellBook . Examples . Introduction . CreatingModules |
| | build-depends: base ^>=4.16.0.0 |
| | hs-source-dirs: src |
| | default -language: Haskell2010 |
| | default -extensions: RecordWildCards |
Now we can use the RecordWildCards extension in any other module we add to our project without adding a LANGUAGE pragma. Similarly, if we start ghci using cabal repl , all of our default extensions will be enabled and we don’t need to use :set to turn them on individually.