The Artima Developer Community
Sponsored Link

Java Buzz Forum
asInt_either

0 replies on 1 page.

Welcome Guest
  Sign In

Go back to the topic listing  Back to Topic List Click to reply to this topic  Reply to this Topic Click to search messages in this forum  Search Forum Click for a threaded view of the topic  Threaded View   
Previous Topic   Next Topic
Flat View: This topic has 0 replies on 1 page
Elliotte Rusty Harold

Posts: 1573
Nickname: elharo
Registered: Apr, 2003

Elliotte Rusty Harold is an author, developer, and general kibitzer.
asInt_either Posted: Jan 20, 2009 9:39 PM
Reply to this message Reply

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

Topic: How to unrar multi-part rar files (*.r00) in Ubuntu 8.10 in Two Simple Steps Previous Topic   Next Topic Topic: Censorship Fail

Sponsored Links



Google
  Web Artima.com   

Copyright © 1996-2019 Artima, Inc. All Rights Reserved. - Privacy Policy - Terms of Use