Created
October 20, 2011 08:50
-
-
Save pimeys/1300714 to your computer and use it in GitHub Desktop.
strToInt and StrToDouble
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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