3 Every line counts

 

This chapter covers

  • Facilitating side effects and input/output within Haskell
  • Using side-effect-free, pure code within impure code
  • Interacting with the operating systems environment
  • Incorporating a command line argument parser into our programs

In the previous chapter, we learned how to construct algorithms to transform strings and explored the basics of programming in Haskell; however, we were only able to test our functionality in GHCi. Now, we want to turn our attention to writing our first real program, which can be invoked from the command line.

When working on the command line or writing automated scripts on Unix-like systems, pipelines of multiple programs are often used for achieving certain tasks, like searching or transforming data. To facilitate interprocess communication easily, streams of texts are used to pass messages from one process to another. This is usually done with the pipe symbol |. This idea is illustrated by figure 3.1.

Figure 3.1 An example of how to transform data using pipes with shell commands
figure

For this to work, there are many tools in the UNIX space that perform basic tasks that, when combined in a pipeline, perform a bigger action. One of these tools is nl, which is short for number lines. Its job is rather simple: print a file and number each line. Essentially, it creates listings for arbitrary text. Here is an example:

3.1 Talking to the outside

3.1.1 Simple actions for input and output

3.1.2 Simulating a loop

3.1.3 Breaking out of a recursive action

3.2 Pure functions inside of actions

3.2.1 Reading and modifying user input

3.2.2 Data flow between pure and impure code

3.3 Reading from the environment

3.3.1 Parsing command line arguments

3.3.2 Encoding errors with Maybe

3.4 Example: Reading and printing a command line argument

3.4.1 The let keyword

3.4.2 Running the program with stack

Summary

sitemap