缩写形式(这将解决我的问题的一个方法至少)如何查看类型是否是Haskell中的类的实例?
我怎样才能做这样的事情:
try_to_show :: a -> String
try_to_show val = if (val is instance of Show) (show val) else "Cannot show"
我可能做这完全错了(的unhaskell方式) ;我只是在学习,所以请让我知道是否有更好的方法来解决这个问题。
上下文:我在写一堆树结构。我想重用我的prettyprint
函数二叉树。尽管不是所有的树都可以使用通用的Node
/Branch
数据类型;不同的树需要不同的额外数据。因此,要重用prettyprint
功能我想创建一个类不同的树会的实例:
class GenericBinaryTree a where
is_leaf :: a -> Bool
left :: a -> a
node :: a -> b
right :: a -> a
这样,他们只需要实现方法来检索左,右,以及当前节点的值,prettyprint没有按” t需要了解内部结构。
然后我得到了到这里:
prettyprint_helper :: GenericBinaryTree a => a -> [String]
prettyprint_helper tree
| is_leaf tree = []
| otherwise = ("{" ++ (show (node tree)) ++ "}") : (prettyprint_subtree (left tree) (right tree))
where
prettyprint_subtree left right =
((pad "+- " "| ") (prettyprint_helper right)) ++ ((pad "`- " " ") (prettyprint_helper left))
pad first rest = zipWith (++) (first : repeat rest)
我也得到了Ambiguous type variable 'a0' in the constraint: (Show a0) arising from a use of 'show'
错误(show (node tree))
这里是最基本的树数据类型和实例的定义(我的其他树木有其他领域的例子但他们无关的通用prettyprint
功能)
data Tree a
= Branch (Tree a) a (Tree a)
| Leaf
instance GenericBinaryTree (Tree a) where
is_leaf Leaf = True
is_leaf _ = False
left (Branch left node right) = left
right (Branch left node right) = right
node (Branch left node right) = node
我可以定义node :: a -> [String]
并处理树的每个实例/类型的字符串化,但是这感觉更整洁。根据prettyprint
,我只需要一个字符串表示法,但如果稍后添加其他通用二叉树函数,我可能需要实际值。
那么我该如何编写这个工作节点值是否是Show
的一个实例呢?或者还有什么其他方式可以解决这个问题?在面向对象的语言中,我可以很容易地检查一个类是否实现了一些东西,或者一个对象是否有方法。
,因为它不是一个需要showable树,我不能使用类似
prettyprint :: Show a => a -> String
,这是一个需要showable树(按功能node
返回)内的值。我也尝试将node
改为Show b => a -> b
而没有运气(还有一堆其他类型的class/preconditions /不管/我甚至不知道我在做什么)。
,你可以让一切都显示的实例:'实例显示,其中显示_ =“”' –
aavogt