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?
The contract of the show method in Haskell is that it produce a string that, when evaluated, yields the value that was shown.
Prelude> let str = "stack\n\noverflow"
Prelude> putStrLn str
stack
overflow
Prelude> putStrLn (show str)
"stack\n\noverflow"
Prelude>
Sounds like you're trying to simulate a ToString method, although some of your terminology is a little confusing.
You can simulate it like this:
{-# LANGUAGE UndecidableInstances, OverlappingInstances,
FlexibleInstances, TypeSynonymInstances #-}
class ToString a where
toString :: a -> String
instance ToString String where
toString = id
instance Show a => ToString a where
toString = show
However, as shown by the LANGUAGE pragmas, this is not very desirable. To really get a feel for what you're trying to do it would be easier if we had more context...
show
shows the variable in the way that you entered it.
Seems pretty regular to me.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With