Welcome to WuJiGu Developer Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.3k views
in Technique[技术] by (71.8m points)

haskell - How to convert arbitrary type to string, without adding extra quotes to strings?

I want to define a function which converts to strings, like the following 'toString':

toString 1 = "1"
toString True = "True"
toString "1" = "1"

Note that 'show' does not do this. By contrast it does the following:

show 1 = "1"
show True = "True"
show "1" = ""1""

That is, it adds extra quotes around strings. In this case I don't want to add extra quotes if I already have a string.

I'm considering using something like:

import Data.Typeable

toString a :: (Show a) => a -> String
toString a
  | typeOf a == typeOf "" = a
  | otherwise = show a

Are there any pitfalls in doing such a weird type-based conditional? Is there some built-in Haskell function that would be better to use instead?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

This sort of ad-hoc polymorphism is permitted through type-classes. However, they will have to be overlapping since you want a catch all case:

{-# LANGUAGE FlexibleInstances, UndecideableInstances #-}

class Print a where
  makeString :: a -> String

instance {-# OVERLAPPING #-} Print String where
  makeString s = s

instance Show a => Print a where
  makeString x = show x

Then, your function is makeString :: Print a => a -> String and it has an instance for everything that has a Show instance. To have the second instance, you need FlexibleInstances (the instance head is not of the usual form) and UndecideableInstances (since the constraint is as general as the instance head, GHC can't be sure that it won't fall into an infinite loop trying to solve these constraints).


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to WuJiGu Developer Q&A Community for programmer and developer-Open, Learning and Share
...