How do I pad string representations of integers in Haskell?

微笑、不失礼 提交于 2020-01-11 01:43:05

问题


I'l looking for an idiomatic (perhaps built-in) way of padding string representations of integers with zeros on the left.

In my case the integers are never more than 99 so

fix r = if length r == 1 then '0':r else r
fix.show <$> [1..15]

works. But I expect there is a better way.

How do I pad string representations of integers in Haskell?


回答1:


printf style formatting is availble via the Text.Printf module:

import Text.Printf

fmt x = printf "%02d" x

Or to special case the formatting of 0:

fmt 0 = "  "
fmt x = printf "%02d" x



回答2:


> (\x -> replicate (3 - length x) '0' ++ x) "2"
"002"
> (\x -> replicate (3 - length x) '0' ++ x) "42"
"042"
> (\x -> replicate (3 - length x) '0' ++ x) "142"
"142"
> (\x -> replicate (3 - length x) '0' ++ x) "5142"
"5142"

The above exploits the fact that replicate returns the empty string on negative argument.




回答3:


For the sake of completeness, I add here a program padding any list of strings with a character passed as an argument.

Rather than taking the maximum of the lengths from the get go, I use an instance of circular programming: if you look carefully, you'll see that n is the result of a computation... in which it is used!

pad :: Char -> [String] -> [String]
pad c xs = ys where
  (ys, n)         = foldr cons ([],0) xs
  cons x (acc, m) = ((replicate (n - m') c ++ x) : acc, max m m')
    where m' = length x


来源:https://stackoverflow.com/questions/32311461/how-do-i-pad-string-representations-of-integers-in-haskell

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