peroni_santo
peroni_santo

Reputation: 367

Removing backslashes when show Strings?

I have parametric method which concats a String onto a parametric input:

foo::(Show a) => a -> String
foo f = show f ++ " string"

it is fine when I don pass in a string, but when I pass in a string I get extra blackslashes.

is there a way i avoid ths?

Upvotes: 1

Views: 956

Answers (3)

David Unric
David Unric

Reputation: 7719

Don't know about "standard" library function but can be simply done with own show-like implementation:

class StrShow a where
    showStr :: a -> String

instance StrShow String where
    showStr = id
instance Show a => StrShow a where
    showStr = show

GHCi> showStr 1
"1"
GHCi> showStr "hello"
"hello"

This way you don't need extra library but have to use lot of ghc's extensions (TypeSynonymInstances, FlexibleInstances, UndecidableInstances, OverlappingInstances) if this is not an issue.

Upvotes: 1

Taneb
Taneb

Reputation: 198

One way of doing this, which isn't very nice but it's certainly possible, is to use the Typeable class.

import Data.Maybe (fromMaybe)
import Data.Typeable (cast)
foo :: (Show a, Typeable a) => a -> String
foo f = fromMaybe (show f) (cast f)

However, this restricts it to members of the Typeable class (which is included in base, so you won't need to depend on any more libraries, and most things will have defined it).

This works by checking if f is a String (or pretending to be a String, which will only happen if someone's been REALLY evil when writing a library), and if it is, returning it, otherwise showing it.

Upvotes: 0

singpolyma
singpolyma

Reputation: 11241

show is not really a toString equivalent but rather an inspect or var_dump equivalent. It's not meant for formatting for human output.

You might consider http://hackage.haskell.org/package/text-format

Upvotes: 4

Related Questions