|
This post originated from an RSS feed registered with Java Buzz
by Elliotte Rusty Harold.
|
Original Post: asInt_either
Feed Title: Mokka mit Schlag
Feed URL: http://www.elharo.com/blog/feed/atom/?
Feed Description: Ranting and Raving
|
Latest Java Buzz Posts
Latest Java Buzz Posts by Elliotte Rusty Harold
Latest Posts From Mokka mit Schlag
|
|
|
Advertisement
|
Real World Haskell, Exercise 4, p. 98:
The asInt_fold function uses error, so its callers cannot handle errors. Rewrite it to fix this problem.
-- file: ch04/IntParse.hs
import Data.Char (digitToInt)
asInt :: String -> Int
asInt ('-':xs) = -1 * asInt xs
asInt xs = foldl step 0 xs
where step acc x = acc * 10 + safeDigitToInt x
safeDigitToInt :: Char -> Int
safeDigitToInt x = if x >= '0' && x <= '9'
then digitToInt x
else error "Non-digit"
asInt_either :: String -> Ei
asInt_either xs = if onlyHasDigits xs
then Main.Right (asInt xs)
else Main.Left ("non-digit '" ++ ((firstNonDigit xs) : "'"))
onlyHasDigits :: String -> Bool
onlyHasDigits [] = True
onlyHasDigits (x:xs) = if x >= '0' && x <= '9'
then onlyHasDigits xs
else False
firstNonDigit :: String -> Char
firstNonDigit [] = '\0'
firstNonDigit (x:xs) = if x <= '0' || x >= '9'
then x
else firstNonDigit xs
data Ei = Right Int
| Left String
deriving (Show)
Doubtless this could be much mproved by someone who knows what they’re doing.

Read: asInt_either