Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I pad string representations of integers in Haskell?

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?

like image 218
orome Avatar asked Aug 31 '15 12:08

orome


2 Answers

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
like image 75
ErikR Avatar answered Oct 16 '22 15:10

ErikR


> (\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.

like image 11
chi Avatar answered Oct 16 '22 13:10

chi