Book Image

Haskell Data Analysis cookbook

By : Nishant Shukla
Book Image

Haskell Data Analysis cookbook

By: Nishant Shukla

Overview of this book

Step-by-step recipes filled with practical code samples and engaging examples demonstrate Haskell in practice, and then the concepts behind the code. This book shows functional developers and analysts how to leverage their existing knowledge of Haskell specifically for high-quality data analysis. A good understanding of data sets and functional programming is assumed.
Table of Contents (14 chapters)
13
Index

Trimming excess whitespace


The text obtained from sources may unintentionally include beginning or trailing whitespace characters. When parsing such an input, it is often wise to trim the text. For example, when Haskell source code contains trailing whitespace, the GHC compiler ignores it through a process called lexing. The lexer produces a sequence of tokens, effectively ignoring meaningless characters such as excess whitespace.

In this recipe, we will use built-in libraries to make our own trim function.

How to do it...

Create a new file, which we will call Main.hs, and perform the following steps:

  1. Import the isSpace :: Char -> Bool function from the built-in Data.Char package:

    import Data.Char (isSpace)
  2. Write a trim function that removes the beginning and trailing whitespace:

    trim :: String -> String
    trim = f . f
      where f = reverse . dropWhile isSpace
  3. Test it out within main:

    main :: IO ()
    main = putStrLn $ trim " wahoowa! "
  4. Running the code will result in the following trimmed string:

    ...