Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there a way to use print with the formats of printf in Haskell?

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]
like image 521
Xzenon Avatar asked Apr 16 '16 00:04

Xzenon


2 Answers

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]]
like image 125
Gurkenglas Avatar answered Oct 12 '22 23:10

Gurkenglas


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.)

like image 39
jamshidh Avatar answered Oct 13 '22 00:10

jamshidh