Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

String formatting in Haskell

Tags:

string

haskell

What is Haskell's equivalent of

string str = string.Format("{0} {1}",10,20); // C#
like image 755
Pratik Deoghare Avatar asked Mar 18 '10 08:03

Pratik Deoghare


5 Answers

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
like image 175
newacct Avatar answered Sep 25 '22 22:09

newacct


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]
like image 27
Dmitry Bespalov Avatar answered Sep 28 '22 22:09

Dmitry Bespalov


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|+"."
like image 24
Shersh Avatar answered Sep 27 '22 22:09

Shersh


Is this what you are looking for?

printf "%d %d" 10 20

See Text.Printf.

like image 30
Oded Avatar answered Sep 29 '22 22:09

Oded


Alternatively you could write

unwords [show 10, show 20]

or even

unwords (map show [10, 20])
like image 39
Adam Dingle Avatar answered Sep 29 '22 22:09

Adam Dingle