You’ve learned how to create data types and records that hold regular Haskell values, and build data types like List that hold recursive values. Another type of value you might sometimes want to hold inside of a data type is a function.

Creating a data type that holds a function looks much like creating any other data type. For example, we can make a data type that holds a function from a String to a pair of strings by saying this:

​  ​ data ​ ​ StringParser ​ = ​ StringParser ​ (​ String ​ -> (​ String ​, ​ String ​))

More often than not, when you see data types that hold a single function, they’ll be records with a field that gives the function some useful name:

​  ​ data ​ ​ StringParser ​ =
​  ​ StringParser ​ { runStringParser :: ​ String ​ -> (​ String ​, ​ String ​) }

The first time you see something like this it can be a little bit hard to understand why you might want to create a data type that holds a function, when we already have first class functions in Haskell without needing to wrap them in a data type. Later on in this book, you’ll learn some Haskell features that will make storing functions in data types more useful, but for now let’s look at a small example of how keeping functions inside of data can help you build abstractions that could be easier for consumers of your code to use.

Sticking with our string parser example, we can imagine that there are any number of different functions that someone might want to write that could split a string into two different parts. One common example might be that we want to take some number of characters off the front of a string. If we were writing a plain function to do that, we might just use the splitAt function. In newer versions of GHC, this will already be defined for you. If you’re using an older version of GHC, you’ll need to import it from the Data.List module by adding import Data.List at the beginning of your module.

Let’s look at a quick non-parser example first, and then we’ll look at how we can turn it into a parser. We’ll start by writing a function called takeCharacters that will take some number of characters off the front of a string. We don’t just want to return those characters though, we also want to return the remainder of the string that we haven’t dealt with yet, so we’ll return a tuple. The first element of the tuple will be the data we just parsed, and the second element will be the data we haven’t yet parsed:

​  ​ module ​ ​ ParserExample ​ ​ where ​
​  ​ import ​ ​ Data.List ​ (​ splitAt ​)
​  
​  takeCharacters :: ​ Int ​ -> ​ String ​ -> (​ String ​,​ String ​)
​  takeCharacters numCharacters inputString =
​  splitAt numCharacters inputString

If we test this out in ghci we can see that our output is a tuple of strings, just as we’d expect:

​  ​ λ ​ takeCharacters 3 ​ "abc12345" ​
​  (​ "abc" ​,​ "12345" ​)

Before we turn this into a StringParser let’s do a little bit of a refactor on this code. We’ll start by adding some parentheses back into the type signature. We can normally leave these out, but they’ll make it easier for us to understand how we’ll turn this version of our function into a StringParser :

​  takeCharacters :: ​ Int ​ -> (​ String ​ -> (​ String ​,​ String ​))
​  takeCharacters numCharacters inputString =
​  splitAt numCharacters inputString

Next, let’s remove inputString from the definition of takeCharacters . Instead, we’ll create a new function from the input string to our parsed tuple, and return that:

​  takeCharacters :: ​ Int ​ -> (​ String ​ -> (​ String ​,​ String ​))
​  takeCharacters numCharacters = stringParser
​  ​ where ​
​  stringParser :: ​ String ​ -> (​ String ​,​ String ​)
​  stringParser inputString =
​  splitAt numCharacters inputString

Now, let’s rewrite stringParser to use a lambda abstraction rather than binding inputString as an argument:

​  takeCharacters :: ​ Int ​ -> (​ String ​ -> (​ String ​,​ String ​))
​  takeCharacters numCharacters = stringParser
​  ​ where ​
​  stringParser :: ​ String ​ -> (​ String ​,​ String ​)
​  stringParser = ​ \ ​inputString ->
​  splitAt numCharacters inputString

It’s a small change to go from this refactored version of takeCharacters to a full StringParser version. We can create a StringParser value from a function with the type String -> (String,String) and that happens to be exactly the type of stringParser function we’ve already defined. We just need to pass the stringParser function into the StringParser value constructor:

​  takeCharacters :: ​ Int ​ -> ​ StringParser ​
​  takeCharacters numCharacters = ​ StringParser ​ stringParser
​  ​ where ​
​  stringParser :: ​ String ​ -> (​ String ​,​ String ​)
​  stringParser = ​ \ ​inputString ->
​  splitAt numCharacters inputString

Finally, let’s refactor this function one last time to be a little bit less verbose. We can remove the intermediate definition of stringParser altogether and pass the lambda directly to the StringParser constructor:

​  takeCharacters :: ​ Int ​ -> ​ StringParser ​
​  takeCharacters numCharacters = ​ StringParser ​ $ ​ \ ​inputString ->
​  splitAt numCharacters inputString

This version of our parser is functionally equivalent to the original version, except now we’ve wrapped the part of the function that transforms strings inside of a StringParser , which will make it somewhat easier to work with.

Next, let’s look at another example of a StringParser we might want to implement: parsing a string by extracting one space-separated word at a time. We can use the break function for this. The break function breaks a string into two parts at the first location where some predicate function that we pass in is true. In this example, we’re breaking the string apart at the first space we encounter. Like splitAt we’ll get back a tuple of lists. The first list will contain everything up until the first space, and the second list will contain everything after the first space.

​  getNextWord :: ​ StringParser ​
​  getNextWord = ​ StringParser ​ $ ​ \ ​someString ->
​  ​ case ​ break (== ​ ' ' ​) someString ​ of ​
​  (nextWord, ​ "" ​) -> (nextWord, ​ "" ​)
​  (nextWord, rest) -> (nextWord, tail rest)

At this point you might be wondering what value StringParser is giving us in exchange for the added complexity of having to wrap part of our functions up in a value constructor. You’ll learn about some more advanced ways we can use these kinds of values later. For now, let’s look at one good example: making it easy to combine our parsers in a general way. For example, we can write a function that runs two parsers, one after another:

​  combineParsers :: ​ StringParser ​ -> ​ StringParser ​ -> ​ StringParser ​
​  combineParsers firstParser secondParser = ​ StringParser ​ $ ​ \ ​someString ->
​  ​ let ​ (_firstPart, firstResult) = runStringParser firstParser someString
​  ​ in ​ runStringParser secondParser firstResult

This lets us easily re-use existing functions that we’ve already written, combining them in interesting ways to create new parsers that we could also join together if we wanted to. For example, let’s look at two different ways that we could combine takeCharacters and getNextWord :

​  getNextWordAfterTenLetters :: ​ StringParser ​
​  getNextWordAfterTenLetters =
​  combineParsers (takeCharacters 10) getNextWord
​  
​  tenLettersAfterTheFirstWord :: ​ StringParser ​
​  tenLettersAfterTheFirstWord =
​  combineParsers getNextWord (takeCharacters 10)

In all of these examples, the first string of our tuple is the one that we’re really interested in. The second string is just holding the rest of the data in case we want to do something else with it, like use it with a different parser. When we’re building things like this, we’ll usually make a helper function that will run a parser for us and just give us the value we’re interested in:

​  parseString :: ​ StringParser ​ -> ​ String ​ -> ​ String ​
​  parseString parser inputString =
​  fst $ runStringParser parser inputString

Now that we have all of these functions, let’s explore them a little bit in ghci . First, we can run our basic parsers to get the values out of them:

​  ​ λ ​ parseString (takeCharacters 5) ​ "Hello, World" ​
​  ​ "Hello" ​
​  ​ λ ​ parseString getNextWord ​ "Haskell Is Fun" ​
​  ​ "Haskell" ​

And we can call our combined versions just as easily:

​  ​ λ ​ parseString tenLettersAfterTheFirstWord ​ "AVeryLongWord 0123456789abcdef" ​
​  ​ "0123456789" ​
​  ​ λ ​ parseString getNextWordAfterTenLetters ​ "123456 hello world" ​
​  ​ "lo" ​

We can even create new ways to parse things ad hoc in the REPL as we’re exploring our code:

​  ​ λ ​ secondWord = combineParsers getNextWord getNextWord
​  ​ λ ​ thirdWord = combineParsers getNextWord secondWord
​  ​ λ ​ parseString thirdWord ​ "one two three four" ​
​  ​ "three" ​

Of course everything that we’ve done in these examples could have been done without putting our functions into a data type, but the data type has made our code a bit easier to work with. We no longer have to keep track of many layers of higher-order functions directly, or pass around a lot of parameters all the time. We can think in terms of the abstract idea of something that parses a string.