Andrew
Andrew

Reputation: 63

Using "printf" on a list in Haskell

How can i use printf over a list? I have a list of numbers and i want to print them all by respecting a format (ex: %.3f). I tried to use map over printf, but it does not work. So, i have no idea. Can somebody help me with this? Any ideas are acceptable. Is there a way to create a string from a list respecting a custom format?

Upvotes: 1

Views: 956

Answers (1)

Mark Karpov
Mark Karpov

Reputation: 7599

printf can produce strings instead of just printing them to stdout. This is because it is overloaded on its result type (it's also part of machinery that makes it variadic).

import Text.Printf

main :: IO ()
main = putStrLn . unwords $ printf "%.3f" <$> ([1..10] :: [Double])

That should do the trick.


BTW, printf is not type safe and can blow at run time. I recommend you use something like formatting.

Upvotes: 1

Related Questions