Skip to content

Instantly share code, notes, and snippets.

@rikusalminen
Forked from pimeys/fold_excersizes.hs
Created October 20, 2011 09:03
Show Gist options
  • Save rikusalminen/1300723 to your computer and use it in GitHub Desktop.
Save rikusalminen/1300723 to your computer and use it in GitHub Desktop.
strToInt and StrToDouble
import Data.Char
strToInt :: String -> Int
strToInt ('+':xs) = strToInt xs
strToInt ('-':xs) = - strToInt xs
strToInt xs =
foldl step 0 xs
where
step acc x = acc * 10 + (digitToInt x)
strToInt _ = undefined
strToDouble :: String -> Double
strToDouble ('-':xs) = -strToDouble xs
strToDouble ('+':xs) = strToDouble xs
strToDouble xs =
whole + frac
where
(l, r) = break (\x -> x == '.') xs
whole = fromIntegral . strToInt $ l
frac = fraction . tail $ r
fraction (ys) = foldr step 0 . map (fromIntegral . digitToInt) $ ys
step acc n = acc * 0.1 + n * 0.1
strToDouble _ = undefined
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment