1

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?

4
  • can you please add what you tried - because I would indeed recommend using map and I don't see why it should not work Commented Apr 16, 2016 at 11:31
  • possible duplicate : stackoverflow.com/questions/36658890/… Commented Apr 16, 2016 at 11:33
  • the result of printf is polymorphic and can't be decided without context, try add more type signatures. Commented Apr 16, 2016 at 11:34
  • 2
    then please edit your question and add an answer or close/delete it - thanks Commented Apr 16, 2016 at 11:39

1 Answer 1

1

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.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.