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

旧城冷巷雨未停 提交于 2019-12-19 16:52:58

问题


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]

回答1:


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]]



回答2:


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



来源:https://stackoverflow.com/questions/36658890/is-there-a-way-to-use-print-with-the-formats-of-printf-in-haskell

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!