I have not yet developed a satisfying coding style in Haskell. In the code snippet below, there is a lot wrong to my taste:
- Helper functions which should be local to
showEngFloat
are defined outside. let ... in
indentation madness- More than 80 columns
Can you show me how this same code can be written in a less indentation and pollution prone way?
I am aware that the name I chose for my function is not well chosen. (show...
functions should return a ShowS
type, right?)
import Numeric
normalize :: Int -> (Int,Int)
normalize dp =
loop dp 0
where
loop dp e
| dp > 3 = loop (dp - 3) (e+3)
| dp < 1 = loop (dp + 3) (e-3)
| otherwise = (dp,e)
toString :: [Int] -> [Char]
toString ia = concat (fmap show ia)
padZeroes nz v = v ++ take nz (repeat '0')
showEngFloat :: RealFloat a => Int -> a -> [Char]
showEngFloat precision x
| x >= 0.0 = calc x
| otherwise = "-" ++ calc (-x)
where
calc n =
let (digits,dotPos0) = floatToDigits 10 n in
let (ndigits,(dotPos1,e)) = (length digits,normalize dotPos0) in
let a
| ndigits >= dotPos1 = toString (take dotPos1 digits)
| otherwise = padZeroes (dotPos1 - ndigits) (toString (take ndigits digits))
in
let b = padZeroes (precision - max dotPos1 ndigits) (toString (drop dotPos1 digits))
in
let c = toString [e] in
a ++ "." ++ b ++ "E" ++ c