Haskell:显示字符串时抑制引号

时间:2012-08-24 03:46:31

标签: haskell

以下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 "hello world" = "hello world"
f HelloWorld = "hello world"

不幸的是,show无法满足这一要求,因为:

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

是否有一个与我上面描述的f类似的函数?

3 个答案:

答案 0 :(得分:17)

首先,看看this question。也许你会对toString函数感到满意。

其次,show是将某些值映射到String的函数。

因此,引用应该被转义是有道理的:

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

是否有一个与我上面描述的f类似的函数?

好像你正在寻找id

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

答案 1 :(得分:3)

要完成最后一个答案,您可以定义以下类:

{-# 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将是printString函数

答案 2 :(得分:1)

我不相信有一个标准类型类可以为你做这个,但一个解决方法是定义一个新类型:

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

然后show (PlainString "hello world") == "hello world"您可以像其他类型一样使用show