2012-08-24 10 views
11

codeを示したときに、文字列の前後に引用符を抑制します:ハスケル:

data HelloWorld = HelloWorld; 
instance Show HelloWorld where show _ = "hello world"; 

hello_world = "hello world" 

main = putStr $ show $ (HelloWorld, hello_world) 

プリント:

(hello world,"hello world") 

私は印刷にそれをたい:

(hello world,hello world) 

私は行動をしたい。すなわち以下のようになります。

私が上記しまし fと同じように動作機能があります

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

残念ながら、showは、前述したように、これを満たしていませんか?

+3

翻訳のために新しいtypeclass(例えば、 'PPrint'という名前)を作成することは、一般に受け入れられています人間が読める 'String'sに変換します。 –

+0

@Clintonはこれらの回答を助けましたか? –

答えて

1

私はあなたのためにこれを行います標準型クラスがあると信じていませんが、1つの回避策はnewtypeの定義するには、次のようになります。そして、

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

show (PlainString "hello world") == "hello world"を、あなたは他のタイプと通常通りshowを使用することができます。

13

まず、this questionをご覧ください。多分toStringの機能に満足しているでしょう。

第2に、showは、ある値をStringにマッピングする関数です。

だから、それは引用の意味をエスケープする必要があります:

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

は、私が上記しましたように動作しますf機能はありますか?あなたがidを探しているよう

は思え:になります

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

と説明した関数f:

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

は、この最後の答えを完了するには、以下のクラスを定義することができますprintString関数