以下代码:
data HelloWorld = HelloWorld;
instance Show HelloWorld where show _ = "hello world";
hello_world = "hello world"
main = putStr $ show $ (HelloWorld, hello_world)
Run Code Online (Sandbox Code Playgroud)
打印:
(hello world,"hello world")
Run Code Online (Sandbox Code Playgroud)
我想要它打印:
(hello world,hello world)
Run Code Online (Sandbox Code Playgroud)
即我想要的行为如下:
f "hello world" = "hello world"
f HelloWorld = "hello world"
Run Code Online (Sandbox Code Playgroud)
不幸的是,show不满足于此,因为:
show "hello world" = "\"hello world\""
Run Code Online (Sandbox Code Playgroud)
有没有像f我上面描述的那样工作的功能?
ДМИ*_*КОВ 19
首先,看看这个问题.也许你会对toString功能感到满意.
其次,show是一个将一些值映射到a的函数String.
因此,引用应该被转义是有道理的:
> show "string"
"\"string\""
Run Code Online (Sandbox Code Playgroud)
有没有像
f我上面描述的那样工作的功能?
好像你在寻找id:
> putStrLn $ id "string"
string
> putStrLn $ show "string"
"string"
Run Code Online (Sandbox Code Playgroud)
为了完成最后一个答案,您可以定义以下类:
{-# 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 ++ ")"
Run Code Online (Sandbox Code Playgroud)
所描述的函数 f 将是 printString 函数
我不相信有一个标准类型类可以为您执行此操作,但一种解决方法是定义一个新类型:
newtype PlainString = PlainString String
instance Show PlainString where
show (PlainString s) = s
Run Code Online (Sandbox Code Playgroud)
然后您就可以像平常一样与其他类型一起show (PlainString "hello world") == "hello world"使用。show
| 归档时间: |
|
| 查看次数: |
10984 次 |
| 最近记录: |