On my quest to acquire further experience in Haskell, I started working with print and printf.
I wanted to try to print an array (well, several, but it's just a start) and I wanted to use the format "%+.4f"
, meaning I would get:
+2.1234 or -1.2345
I noticed however that it's pretty hard to print an array using printf, so I tried switching to print. It seems easier to print a list this way, but I'm not sure how I can print the elements of the list using the same format I used for printf.
My list looks something like this:
[-1.2, 2.3, 4.7, -6.850399]
Two variants that should do the same, using the two possible return types of printf:
putStrLn $ concatMap (printf "%+.4f\n") [-1.2, 2.3, 4.7, -6.850399]
mapM_ (printf "%+.4f\n") [-1.2, 2.3, 4.7, -6.850399]
Edit: For traversing two lists deep:
putStrLn $ (concatMap . concatMap) (printf "%+.4f\n") [[-1.2, 2.3], [4.7, -6.850399]]
(mapM_ . mapM_) (printf "%+.4f\n") [[-1.2, 2.3], [4.7, -6.850399]]
You can use the functions in the Numeric
module. For instance "%+.4f" can be represented as
formatFloat x = showFFloat (Just 4) x ""
You can then map this function over your list, to get a list of Strings.
> map formatFloat [-1.2, 2.3, 4.7, -6.850399]
["-1.2000","2.3000","4.7000","-6.8504"]
(since these are already strings I'd use putStrLn
instead of print
to show the output.)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With