Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Haskell: Suppress quotes around strings when shown

Tags:

haskell

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?

like image 764
Clinton Avatar asked Aug 24 '12 03:08

Clinton


3 Answers

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"
like image 94
ДМИТРИЙ МАЛИКОВ Avatar answered Oct 24 '22 12:10

ДМИТРИЙ МАЛИКОВ


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

like image 45
fp4me Avatar answered Oct 24 '22 12:10

fp4me


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.

like image 2
ajd Avatar answered Oct 24 '22 12:10

ajd