Real World Haskell Exercise - Ch 4


/ Published in: Haskell
Save to your folder(s)

The first fold exercise from RWH, Chapter 4


Copy this code and paste it in your HTML
  1. {- Ex 1: Use a fold (choosing the appropriate fold will
  2.   make your code much simpler) to rewrite and improve upon
  3.   the asInt function from the section called “Explicit recursion”.
  4.  
  5.   Your function should behave as follows.
  6.  
  7.   ghci> asInt_fold "101"
  8.   101
  9.   ghci> asInt_fold "-31337"
  10.   -31337
  11.   ghci> asInt_fold "1798"
  12.   1798
  13.  
  14.   Extend your function to handle the following kinds of exceptional conditions by calling error.
  15.  
  16.   ghci> asInt_fold ""
  17.   0
  18.   ghci> asInt_fold "-"
  19.   0
  20.   ghci> asInt_fold "-3"
  21.   -3
  22.   ghci> asInt_fold "2.7"
  23.   *** Exception: Char.digitToInt: not a digit '.'
  24.   ghci> asInt_fold "314159265358979323846"
  25.   564616105916946374
  26. -}
  27. import Data.Char (digitToInt) -- we'll need ord
  28. import Data.List (foldl')
  29.  
  30. -- powTen was originally a one-liner. I'm trying to guard against an int overflow,
  31. -- but haven't yet found a way to successfully do so.
  32. asInt_fold :: String -> Int
  33. asInt_fold [] = error "String is empty"
  34. asInt_fold "-" = error "dash is not a number"
  35. asInt_fold ('-':xs) = (-1) * asInt_fold xs
  36. asInt_fold str = foldl' powTen 0 str
  37. where maxis = maxBound::Int
  38. powTen n ch
  39. | n > (maxis) = error "overflow of int"
  40. | otherwise = n * 10 + (digitToInt ch)

Report this snippet


Comments

RSS Icon Subscribe to comments

You need to login to post a comment.