【发布时间】:2013-11-07 19:36:08
【问题描述】:
由于a former question,一直在研究haskell中的硬数据类型和类型类,想知道a是否有某个类和数据类型,
例如:
class Example a where
function :: a -> Int
和
data Tree a = EmptyTree
| Node a (Tree [a]) (Tree [a]) deriving (Show, Read, Eq)
如何在数据类型树中使用类示例中的函数?
我认为这与实例有关,但这是否正确?
instance Example where
function :: a -> Int, and then i define the function here?
你能举个例子吗?
【问题讨论】:
-
你回答了你自己的问题,但是:如果你的意思是整数,一定要写
Int,而不是int,你会得到的错误信息太混乱了。 -
哈哈,谢谢@Ingo!所以基本上类类型只是为了定义函数,然后应该写在实例中,是这样吗?
-
Yerewan 电台的回答:原则上是的,但是 a) 类型类不是类型,记住这一点很重要,b) 您可以在类定义中编写函数的默认实现。
-
instance Example where function x = 42。 -- 使用您的Tree a数据类型,顶部Node将包含a值,第二级节点将具有[a]、第三级-[[a]]等类型的列表。在每个节点中都有[a]应该是data Tree a = EmptyTree | Node [a] (Tree a) (Tree a)
标签: haskell tree functional-programming