【问题标题】:Haskell Data Types and type classesHaskell 数据类型和类型类
【发布时间】: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


【解决方案1】:

您的实例实现应如下所示:

instance Example (Tree a) where
  function EmptyTree = ...
  function (Node val left right) = ...

【讨论】:

  • 所以基本上如果希望我的数据在通过类示例中定义的函数输入树时进行排序,有可能吗?
  • @dcarou 是的,它是,但我猜你正试图将树的属性表达为树中最可能的数据属性。但也许我错了....
  • @dcarou - 我不确定你的意思 - 你希望树中的值具有可比性吗?您可以将Ord 约束添加到Tree 的实例,即instance Ord a => Example (Tree a)
【解决方案2】:

从你最近提出的另一个问题来看,我认为你想要这样的东西:

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 ...

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2018-11-29
    • 1970-01-01
    • 2022-08-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多