Search icon CANCEL
Subscription
0
Cart icon
Your Cart (0 item)
Close icon
You have no products in your basket yet
Save more on your purchases now! discount-offer-chevron-icon
Savings automatically calculated. No voucher code required.
Arrow left icon
Explore Products
Best Sellers
New Releases
Books
Videos
Audiobooks
Learning Hub
Conferences
Free Learning
Arrow right icon
Arrow up icon
GO TO TOP
Haskell Data Analysis cookbook

You're reading from   Haskell Data Analysis cookbook Explore intuitive data analysis techniques and powerful machine learning methods using over 130 practical recipes

Arrow left icon
Product type Paperback
Published in Jun 2014
Publisher
ISBN-13 9781783286331
Length 334 pages
Edition 1st Edition
Languages
Arrow right icon
Author (1):
Arrow left icon
Nishant Shukla Nishant Shukla
Author Profile Icon Nishant Shukla
Nishant Shukla
Arrow right icon
View More author details
Toc

Table of Contents (14) Chapters Close

Preface 1. The Hunt for Data FREE CHAPTER 2. Integrity and Inspection 3. The Science of Words 4. Data Hashing 5. The Dance with Trees 6. Graph Fundamentals 7. Statistics and Analysis 8. Clustering and Classification 9. Parallel and Concurrent Design 10. Real-time Data 11. Visualizing Data 12. Exporting and Presenting Index

Catching I/O code faults

Making sure our code doesn't crash in the process of data mining or analysis is a substantially genuine concern. Some computations may take hours, if not days. Haskell gifts us with type safety and strong checks to help ensure a program will not fail, but we must also take care to double-check edge cases where faults may occur.

For instance, a program may crash ungracefully if the local file path is not found. In the previous recipe, there was a strong dependency on the existence of input.txt in our code. If the program is unable to find the file, it will produce the following error:

mycode: input.txt: openFile: does not exist (No such file or directory)

Naturally, we should decouple the file path dependency by enabling the user to specify his/her file path as well as by not crashing in the event that the file is not found.

Consider the following revision of the source code.

How to do it…

Create a new file, name it Main.hs, and perform the following steps:

  1. First, import a library to catch fatal errors as follows:
    import Control.Exception (catch, SomeException)
  2. Next, import a library to get command-line arguments so that the file path is dynamic. We use the following line of code to do this:
    import System.Environment (getArgs)
  3. Continuing as before, define and implement main as follows:
    main :: IO ()
    main = do
  4. Define a fileName string depending on the user-provided argument, defaulting to input.txt if there is no argument. The argument is obtained by retrieving an array of strings from the library function, getArgs :: IO [String], as shown in the following steps:
    args <- getArgs
      let filename = case args of
        (a:_) -> a
            _ -> "input.txt"
  5. Now apply readFile on this path, but catch any errors using the library's catch :: Exception e => IO a -> (e -> IO a) -> IO a function. The first argument to catch is the computation to run, and the second argument is the handler to invoke if an exception is raised, as shown in the following commands:
      input <- catch (readFile fileName)
        $ \err -> print (err::SomeException) >> return ""
  6. The input string will be empty if there were any errors reading the file. We can now use input for any purpose using the following command:
      print $ countWords input
  7. Don't forget to define the countWords function as follows:
    countWords input = map (length.words) (lines input)

How it works…

This recipe demonstrates two ways to catch errors, listed as follows:

  • Firstly, we use a case expression that pattern matches against any argument passed in. Therefore, if no arguments are passed, the args list is empty, and the last pattern, "_", is caught, resulting in a default filename of input.txt.
  • Secondly, we use the catch function to handle an error if something goes wrong. When having trouble reading a file, we allow the code to continue running by setting input to an empty string.

There's more…

Conveniently, Haskell also comes with a doesFileExist :: FilePath -> IO Bool function from the System.Directory module. We can simplify the preceding code by modifying the input <- … line. It can be replaced with the following snippet of code:

exists <- doesFileExist filename
input <- if exists then readFile filename else return ""

In this case, the code reads the file as an input only if it exists. Do not forget to add the following import line at the top of the source code:

import System.Directory (doesFileExist)
You have been reading a chapter from
Haskell Data Analysis cookbook
Published in: Jun 2014
Publisher:
ISBN-13: 9781783286331
Register for a free Packt account to unlock a world of extra content!
A free Packt account unlocks extra newsletters, articles, discounted offers, and much more. Start advancing your knowledge today.
Unlock this book and the full library FREE for 7 days
Get unlimited access to 7000+ expert-authored eBooks and videos courses covering every tech area you can think of
Renews at $19.99/month. Cancel anytime