Haskell实例模拟? [英] Haskell instanceof analogue?

查看:105
本文介绍了Haskell实例模拟?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述



我想要一个函数

  show2 ::(Show a)=> a  - >字符串

这将返回 show a a ,但 a 如果a本身 String
我如何实现它?



如果这个函数已经在某个地方实现了,但是我仍然希望看到一个实现的例子。

用这段肮脏而危险的代码来做这件事:

  class显示a where 
show2 :: a - >字符串

实例显示字符串其中
show2 = id

实例(显示a)=> Showable a where
show2 = show

您需要 -XOverlappingInstances - XFlexibleInstances -XUndecidableInstances 来编译和使用它。

  * Main> show2abc
abc
* Main> show2 3
3


I am new to Haskell, so my question is probably stupid.

I want a function

show2 :: (Show a) => a -> String

which would return show a for any a, but a if a is itself String. How can I implement it?

P.S. it is great if this function is already implemented somewhere, but I still want to see an example of the implementation.

解决方案

You can do this with this piece of dirty and dangerous code:

class Showable a where
  show2 :: a -> String

instance Showable String where
  show2 = id

instance (Show a) => Showable a where
  show2 = show

You need -XOverlappingInstances -XFlexibleInstances -XUndecidableInstances to compile and use it.

*Main> show2 "abc"
"abc"
*Main> show2 3
"3"

这篇关于Haskell实例模拟?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆