Haskell数据类型和类型类
由于,我一直在研究haskell中的硬数据类型和类型类,我想知道a是否有特定的类和数据类型 例如:Haskell数据类型和类型类,haskell,tree,functional-programming,Haskell,Tree,Functional Programming,由于,我一直在研究haskell中的硬数据类型和类型类,我想知道a是否有特定的类和数据类型 例如: class Example a where function :: a -> Int 及 如何在数据类型树中使用类示例中的函数 我认为这与实例有关,但这是正确的吗 instance Example where function :: a -> Int, and then i define the function here? 您能给我举个例子吗?您的实例实现应该如下所示
class Example a where
function :: a -> Int
及
如何在数据类型树中使用类示例中的函数
我认为这与实例有关,但这是正确的吗
instance Example where
function :: a -> Int, and then i define the function here?
您能给我举个例子吗?您的实例实现应该如下所示:
instance Example (Tree a) where
function EmptyTree = ...
function (Node val left right) = ...
从你最近问的另一个问题来看,我认为你想要这样的东西:
class Order a where
order :: a -> Int
insert :: Order k => k -> Tree k -> Tree k
insert key tree
| order key == 0 = ..do work for items of order 0 ...
| otherwise = ..do work for items of higher order ...
你回答了你自己的问题,但是:如果你是指整数,一定要写
Int
,而不是Int
,你将收到的错误消息将太令人困惑。哈哈,谢谢@Ingo!所以基本上,类类型只是用来定义函数,然后它们应该在实例中编写,对吗?Yerewan电台的回答:原则上是的,但是a)类型类不是类型,记住这一点很重要,b)您可以在类定义中编写函数的默认实现。函数x=42的实例--使用树a
数据类型,顶部的节点将包含a
值,第二级节点将具有类型[a]
、第三级[[a]]
等的列表。要在每个节点中具有列表[a]
,它应该是数据树a=EmptyTree |节点[a](树a)(树a)
基本上,如果a希望我的数据在通过类示例中定义的函数输入到树中时进行排序,是否可能?@dcarou是的,但我猜您试图将最有可能是树中数据的属性表示为树的属性。但也许我错了…@dcarou-我不知道你的意思-你希望树中的值具有可比性吗?您可以向树的实例添加Ord
约束,即实例Ord a=>示例(树a)
class Order a where
order :: a -> Int
insert :: Order k => k -> Tree k -> Tree k
insert key tree
| order key == 0 = ..do work for items of order 0 ...
| otherwise = ..do work for items of higher order ...