【问题标题】:Haskell: Suppress quotes around strings when shownHaskell:显示时禁止字符串周围的引号
【发布时间】:2012-08-24 03:46:30
【问题描述】:

以下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 这样工作的函数?

【问题讨论】:

  • 创建一个新的类型类(例如命名为PPrint)以翻译成人类可读的Strings 是公认的好习惯。
  • @Clinton 这些答案有帮助吗?
  • f HelloWorld = "hello world" 需要词法分析和大小写更改。正则表达式可能是票。

标签: haskell


【解决方案1】:

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

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

所以,引号应该被转义是有道理的:

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

有没有像我上面描述的f 这样工作的函数?

好像你在找id:

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

【讨论】:

    【解决方案2】:

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

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

    【讨论】:

      【解决方案3】:

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

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

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

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2020-06-10
        • 2018-10-29
        • 1970-01-01
        • 2011-01-27
        • 2018-04-21
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多