AJChapman / formatting

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

Adding String interface? #5

Closed Icelandjack closed 10 years ago

Icelandjack commented 10 years ago

This may be controversial (“String incompatible (probably a plus)”) but I think it's worth discussing.

String is still in use and it would be nice to be able to use the library without OverloadedStrings, many beginners avoid language extensions and the error messages from overloading strings can be daunting so adding an option for String may lower the barrier to entry. Currently Text.Printf.printf works with strings so formatting can't be used as a drop-in replacement.

Since overloaded strings are used to interpret Holey as a string I see three ways:

To discourage String usage by default it can be put in Formatting.String.

Icelandjack commented 10 years ago

Here's an example from the second idea without using OverloadedStrings, it's of course messier but that may serve as an encouragement to switch to Text :)

ghci> :set -XNoOverloadedStrings 
ghci> import Data.String
ghci> let r = fromString
ghci> format (r"hi-" % int % r"!") 5
"hi-5!"
chrisdone commented 10 years ago

I'm not quite sure exactly what this issue is addressing. Is it only against the OverloadedStrings extension?

Icelandjack commented 10 years ago

The issue is mainly about also having a formatting function that returns the more familiar String without having to unpack it manually, the function definition is simple enough and can be used with and without OverloadedStrings:

strFormat :: Holey Builder String a -> a
strFormat m = runHM m (T.unpack . T.toLazyText)

And so can the normal format:

ghci> let r = fromString 
ghci> strFormat (r"Name: "%s%r", age: "%int) "Emma" 24
"Name: Emma, age: 24"
it :: String
ghci> format (r"Name: "%s%r", age: "%int) "Emma" 24
"Name: Emma, age: 24"
it :: Text
ghci> :set -XOverloadedStrings
ghci> take 5 (strFormat ("Name: "%s%", age: "%int) "Emma" 24)
"Name:"
it :: [Char]

So adding strFormat is fairly orthogonal to OverloadedStrings.

chrisdone commented 10 years ago

This is fine. I'm not sure I want to cater to people using String preemptively… maybe if some newbie asks for it. Right now this seems hypothetical only. =)

Icelandjack commented 10 years ago

Fair enough. I thought it was a bigger change initially but avoiding OverloadedStrings can be done with a single definition … = fromString and strFormat is easy enough to define. It would be nice to give people fewer excuses to use the not-so-type-safe printf :) I'll close it