Skip to content

Instantly share code, notes, and snippets.

@pimeys
Created October 20, 2011 08:50
Show Gist options
  • Save pimeys/1300714 to your computer and use it in GitHub Desktop.
Save pimeys/1300714 to your computer and use it in GitHub Desktop.
strToInt and StrToDouble
import Data.Char
strToInt :: String -> Int
strToInt [] = 0
strToInt (x:xs)
| x == '-' = - strToInt xs
| otherwise = foldl step 0 (x:xs)
where step acc x = acc * 10 + (digitToInt x)
strToDouble :: String -> Double
strToDouble [] = 0
strToDouble (x:xs)
| x == '-' = left - right
| otherwise = left + right
where broken = break (\x -> x == '.') (x:xs)
left = fromIntegral . strToInt $ fst broken
right = fraction . tail $ snd broken
fraction (ys) = foldr step 0 $ strToIntAry ys
strToIntAry [] = []
strToIntAry (z:zs) = (fromIntegral $ digitToInt z) : strToIntAry zs
step acc n = acc * 0.1 + n * 0.1
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment