AJChapman / formatting

Format strings type-safely with combinators
BSD 3-Clause "New" or "Revised" License
164 stars 39 forks source link

Adding formatters for numeric bases #4

Closed Icelandjack closed 10 years ago

Icelandjack commented 10 years ago

Currently base-16 is the only formatter supported like in text-format — unless there is some reason not to it's easy to define other bases using showIntAtBase from Numeric (similar to Numeric.Lens):

toBase :: (Show a, Integral a) => a -> a -> String
toBase(numBase) n = showIntAtBase numBase intToDigit n ""

base :: (Show a, Integral a) => a -> Format a
base(numBase) = later (T.fromText . T.pack . toBase(numBase))

I made the following as a simple proof of concept, if you're okay with adding it to the project I'll submit a request:

ghci> format (base(2) % " " % base(8) % " " % base(16)) 255 255 255
"11111111 377 ff"
ghci> format (base'(2) % " " % base'(8) % " " % base'(16)) 255 255 255
"0b11111111 0o377 0xff"

with

base'(2)  = "0b" % base(2)
base'(8)  = "0o" % base(8)
base'(16) = "0x" % base(16)
base'(b)  = base(b)

Then specialized bases would be trivially implemented:

bin  = base(2)
bin' = base'(2)
oct  = base(8)
oct' = base'(8)
hex' = base'(16)

As efficiency is concerned, text-format doesn't export integer but a more efficient version for arbitrary bases or specialized for certain base like hexadecimal can be added later.

I'm not sure about the names of the prime functions, if this looks fine I'll add it.

Icelandjack commented 10 years ago

One issue is that showIntAtBase adds Show and Integral constraints while hex only adds Integral.

chrisdone commented 10 years ago

Thoughts:

I'll definitely accept the base combinator and bin and oct.

Icelandjack commented 10 years ago

Yes I'll leave hex alone and Show doesn't seem to be an issue.