What is Haskell's equivalent of
string str = string.Format("{0} {1}",10,20); // C#
There is a Printf module in GHC.
import Text.Printf
str :: String
str = printf "%d %d" 10 20
however it is probably simpler to just do
str = show 10 ++ " " ++ show 20
ERROR filename.hs:3:Cannot justify constraints in explicitly typed binding. I am using WinHugs.Text.Printf.printf returns an IO action (IO ()) when fully applied, not a String.String. It can return any type that is PrintfType.You could use the format function provided by the text-format-simple package:
import Text.Format
format "{0} {1}" [show 10, show 20]
This function has the signature:
format :: String -> [String] -> String
So all you need is provide your parameters as strings.
Another example:
format "Some {0} believes that 1 + 1 = {1}." ["people",show 10]
Data.Text as its output, rather than String. As I need to integrate with existing code that relies on String, this would require an unnecessary conversion for me. Is there an alternative that produces a String output and supports a format specifier that allows you to change the order of fields in the output?Putting answer here in case somebody searching for formatting libraries in Haskell on StackOverflow. There's type-safe and fast formatting library called fmt now. With it you can write code like this:
> "There are "+|n|+" million bicycles in "+|city|+"."
Ambiguous type variable ‘t0’ arising from a use of ‘printf’ prevents the constraint ‘(Text.Printf.PrintfArg t0)’ from being solved.
{0, 10}?