4 Line Numbering Tool

 

This chapter covers

  • Reading files from the file system
  • Parameterizing the behavior of higher-order functions by using function arguments
  • Using algebraic data structures to encode possible options
  • Bundling code as an executable

In the last chapter, we have laid the groundwork for a tool that is able to number lines from a given file.

We have learned how we can read arguments from the user. So now, we can start thinking about how to read from a file and how to get the individual lines of the file’s content.

This chapter starts by providing a discussion on reading files and transforming the read contents. Following this, we will write a general function whose control and data flow are influenced by functions given as arguments. Then we will learn how to encode options with algebraic data structures and finish the chapter by completing our tool from the last chapter.

4.1 Reading files and transforming their content

So, we need some IO action to perform this task. Haskell provides rudimentary functionality around working with files with two actions:

readFile :: FilePath -> IO String

writeFile :: FilePath -> String -> IO ()

4.1.1 Writing a pure library

4.1.2 Hiding auxiliary arguments

4.2 Parametrized behavior in higher-order functions

4.2.1 Partial function application

4.3 Algebraic data structures as an encoding of possibilities

4.3.1 Sum types or tagged unions

4.3.2 Don’t repeat yourself

4.3.3 The zip function

4.3.4 Working with missing values

4.3.5 Printing a list of values with mapM

4.4 From library to executable

4.4.1 Encoding and parsing command line options

4.4.2 An overview of the project

4.5 Summary