我是 Haskell 的新手,所以我的问题可能很愚蠢。
我想要一个功能
show2 :: (Show a) => a -> String
这将返回
show a
对于任何 a
,但是 a
如果 a 本身是 String
.我该如何实现?
附言如果这个功能已经在某处实现了,那就太好了,但我仍然想看一个实现的例子。
最佳答案
您可以使用 cast
来自 Data.Typeable
show2 :: (Typeable a, Show a) => a -> String
show2 s = maybe (show s) id ms
where ms = cast s :: Maybe String
关于Haskell 实例模拟?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29284765/