有没有办法在Haskell中使用printf格式的打印? [英] Is there a way to use print with the formats of printf in Haskell?
问题描述
为了获得Haskell的进一步经验,我开始使用print和printf。
我想尝试打印一个数组(好几个,但这只是一个开始),我想用格式%+ .4f
,这意味着我会得到:
+2.1234或-1.2345
然而,我注意到使用printf打印数组非常困难,所以我尝试切换到打印。以这种方式打印列表似乎更容易,但我不确定如何使用与printf相同的格式打印列表元素。
我的清单看起来像这样:
[ - 1.2,2.3,4.7,-6.850399]
$ c $ >
putStrLn $ concatMap(printf%+。4f\\\
)[-1.2,2.3,4.7,-6.850399]
mapM_(printf%+。4f \ n)[-1.2,2.3,4.7,-6.850399]
编辑:为了遍历两个列表:
putStrLn $(concatMap。concatMap)(printf%+。4f \ n)[[-1.2,2.3],[4.7,-6.850399]]
(mapM_。mapM_)(printf%+。4f\\\
)[[-1.2,2.3],[ 4.7,-6.850399]]
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]]
这篇关于有没有办法在Haskell中使用printf格式的打印?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!