7 Working with CSV files

 

This chapter covers

  • Haskell’s record syntax and how to use it
  • Using smart constructors to safely create data structures satisfying some property
  • Creating instances for type classes
  • Defining your own type classes with default implementations

In the last chapter, we tackled a search problem and wrote some powerful artificial intelligence for a children’s game. In this chapter, however, we want to take care of earnest business, and nothing screams business like spreadsheets! Don’t worry, we will not deal with any data directly. As programmers, we obviously want to automate such tasks, and the easiest way for us to deal with data in spreadsheet form is using comma-separated values (CSV) files.

In this chapter, we will cover how to parse such files, extract meaningful data from them, and work effectively with structured data. We will learn how to generalize the appending and slicing of data as well as how to bring type classes into the mix to help us write our program.

This chapter will begin with an introduction to CSV files and how to model them using Haskell’s record syntax. We will learn how to encode errors using the Either type. We will cover using the dollar operator and certain language extensions to simplify our syntax. Following this, we will create our own type classes to generalize the use case for our data types. All the while, we will learn about the type classes Semigroup and Monoid, what they represent, and what they are used for.

7.1 Modeling CSV data

7.1.1 Record syntax

7.1.2 Encoding errors with Either

7.2 Smart constructors

7.2.1 Ensuring a property at the time of construction

7.2.2 Providing an unsafe alternative

7.2.3 The dollar sign operator

7.3 Using type classes

7.3.1 Semigroup and Monoid

7.3.2 The IsString type class

7.4 Creating a new type class

7.4.1 A type class for slicing data structures

7.4.2 Re-exporting modules

Summary