我试图在show上编写一个变体,通过不包括“并直接返回字符串”来处理与其他Show实例不同的字符串。但我不知道该如何做。模式匹配?警卫?我在任何文档中都找不到这方面的任何内容。
下面是我尝试过的,它没有编译:
show_ :: Show a => a -> String
show_ (x :: String) = x
show_ x = show x发布于 2014-10-12 21:01:09
TL;DR:
复制前奏的方式,并使用showList_作为类函数为列表生成实例,这样您就可以重写字符串的定义。
警告
作为记录,使用新类型包装器的wowofbob's answer是我在现实生活中使用的简单、干净的解决方案,但我认为,也可以看看前奏曲是如何做到这一点的。
默认情况下,插入逗号
在序言中这样做的方式是使Show类具有一个显示列表的函数,并具有可以覆盖的默认定义。
import Data.List (intercalate)我将使用intercalate :: [a] -> [[a]] -> [a]在内容之间加上逗号:
ghci> intercalate "_._" ["intercalate","works","like","this"]
"intercalate_._works_._like_._this"创建一个showList_类函数,并默认显示和逗号分隔的列表.
因此,现在使用showList函数的默认实现的类,更重要的是,一个只使用普通show函数的默认show实现。为了能够使用该类型,我们必须坚持该类型已经在Show类型中,但据我所知,这是可以接受的。
class Show a => Show_ a where
show_ :: a -> String
showList_ :: [a] -> String
show_ = show
showList_ xs = '[' : intercalate ", " (map show_ xs) ++ "]"real Show直接使用String -> String类型的函数,而不是String,这是因为效率方面的原因,还有一个优先级参数来控制括号的使用,但是为了简单起见,我将跳过所有这些。
自动生成列表实例
现在,我们可以使用showList函数为列表提供一个实例:
instance Show_ a => Show_ [a] where
show_ xs = showList_ xsShow a =>超类使实例变得非常简单。
现在我们来看看一些例子。因为我们的默认show_实现,我们不需要执行任何实际的编程,除非我们想要覆盖默认,因为我们将为Char,因为String ~ [Char]。
instance Show_ Int
instance Show_ Integer
instance Show_ Double
instance Show_ Char where
show_ c = [c] -- so show_ 'd' = "d". You can put show_ = show if you want "'d'"
showList_ = id -- just return the string在实践中:
现在,在ghci中隐藏"对输出没有多大用处,因为默认的show函数用于此,但是如果我们使用putStrLn,那么引号就会消失:
put :: Show_ a => a -> IO ()
put = putStrLn . show_ghci> show "hello"
"\"hello\""
ghci> show_ "hello"
"hello"
ghci> put "hello"
hello
ghci> put [2,3,4]
[2, 3, 4]
ghci> https://stackoverflow.com/questions/26328121
复制相似问题