2012-08-24 5 views
11

qui suit code:Haskell: Réprimer guillemets autour des chaînes lorsque montré

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") 

Je voudrais qu'il imprimer:

(hello world,hello world) 

-à-dire le comportement que je veux comme le suivant:

f "hello world" = "hello world" 
f HelloWorld = "hello world" 

Malheureusement, show ne satisfait pas, comme:

show "hello world" = "\"hello world\"" 

Y at-il une fonction qui fonctionne comme f que je l'ai décrit ci-dessus?

+3

Il est généralement accepté de créer une nouvelle classe de types (par exemple, appelée 'PPrint') pour les traductions à 'String's lisible par l'homme. –

+0

@Clinton a fait l'une de ces réponses aider? –

Répondre

1

Je ne crois pas qu'il y ait une norme qui classe de types faire pour vous, mais une solution de contournement serait de définir un newtype:

newtype PlainString = PlainString String 
instance Show PlainString where 
    show (PlainString s) = s 

Ensuite show (PlainString "hello world") == "hello world" et vous pouvez utiliser show comme d'habitude avec d'autres types .

13

Tout d'abord, jetez un oeil à this question. Peut-être que vous serez satisfait de la fonction toString.

Deuxièmement, show est une fonction qui mappe une valeur à String.

Ainsi, il est logique que cite doit être échappé:

> show "string" 
"\"string\"" 

Y at-il une fonction qui fonctionne comme f que je l'ai décrit ci-dessus?

On dirait que vous cherchez id:

> putStrLn $ id "string" 
string 
> putStrLn $ show "string" 
"string" 
3

Pour compléter cette dernière réponse, vous pouvez définir la classe suivante:

{-# 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 ++ ")" 

et la fonction f décrit sera la Fonction printString

Questions connexes