Book Image

Haskell Data Analysis Cookbook

By : Nishant Shukla
Book Image

Haskell Data Analysis Cookbook

By: Nishant Shukla

Overview of this book

Table of Contents (19 chapters)
Haskell Data Analysis Cookbook
Credits
About the Author
About the Reviewers
www.PacktPub.com
Preface
Index

Reading a number from another base


Decimal, binary, and hexadecimal are widely used numeral systems that are often represented using a string. This recipe will show how to convert a string representation of a number in an arbitrary base to its decimal integer. We use the readInt function, which is the dual of the showIntAtBase function described in the previous recipe.

How to do it...

  1. Import readInt and the following functions for character manipulation as follows:

    import Data.Char (ord, digitToInt, isDigit)
    import Numeric (readInt)
  2. Define a function to convert a string representing a number in a particular base to a decimal integer as follows:

    str 'base' b = readInt b isValidDigit letterToNum str
  3. Define the mapping between letters and numbers for larger digits, as shown in the following code snippet:

    letterToNum :: Char -> Int
    letterToNum d
      | isDigit d = digitToInt d
      | otherwise = ord d - ord 'a' + 10
                 
    isValidDigit :: Char -> Int
    isValidDigit d = letterToNum d >= 0
  4. Print...