The show function in Haskell doesn't seem to do what it should:
Prelude> let str = "stack\n\noverflow"
Prelude> putStrLn str
stack
overflow
Prelude> show str
"\"Stack\\n\\n\\noverflow\""
Prelude>
When I declare functions, I normally put the type signatures as Show, which doesn't deal with newlines correctly. I want it to treat \n
as newlines, not literally "\n"
. When I change the type to String, the functions work fine. But I'd have to implement a seperate function for integers, floats, etc, etc.
For example, I may declare a function:
foo :: (Show x) => x -> IO ()
foo x = do
putStrLn $ show x
... and call it this way:
foo "stack\n\noverflow"
foo 6
foo [1..]
How would I get the function to return what's expected? I.e. which function is similar to show
but can return strings containing newlines?
repr()
in Python andinspect
in Ruby, if you've used those languages before.repr
is very apt, becauseshow
usually produces output whichread
could then parse and construct the original object from. It's not pretty-printing, it's serialization,Show
seems like an obvious constraint as it gives a means for ensuring atoString
equivalent function can be applied. It's not so much thatshow
has the wrong behaviour as there is no commonly / obviously applicabletoString
for assembling Strings into documents.