The following code:
data HelloWorld = HelloWorld;
instance Show HelloWorld where show _ = "hello world";
hello_world = "hello world"
main = putStr $ show $ (HelloWorld, hello_world)
Prints:
(hello world,"hello world")
I'd like it to print:
(hello world,hello world)
i.e. I want behaviour like the following:
f "hello world" = "hello world"
f HelloWorld = "hello world"
Unfortunately, show
does not satisfy this, as:
show "hello world" = "\"hello world\""
Is there a function that works like f
that I've described above?
Firstly, take a look at this question. Maybe you will be satisfied with toString
function.
Secondly, show
is a function that maps some value to a String
.
So, it makes sense that quotes should be escaped:
> show "string"
"\"string\""
Is there a function that works like
f
that I've described above?
Seems like you're looking for id
:
> putStrLn $ id "string"
string
> putStrLn $ show "string"
"string"
To complete this last answer , you can define the following class :
{-# LANGUAGE TypeSynonymInstances #-}
class PrintString a where
printString :: a -> String
instance PrintString String where
printString = id
instance PrintString HelloWorld where
printString = show
instance (PrintString a, PrintString b) => PrintString (a,b) where
printString (a,b) = "(" ++ printString a ++ "," ++ printString b ++ ")"
and the function f described will be the printString function
I don't believe there is a standard typeclass that will do this for you, but one workaround would be to define a newtype:
newtype PlainString = PlainString String
instance Show PlainString where
show (PlainString s) = s
Then show (PlainString "hello world") == "hello world"
and you can use show
as normal with other types.
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