haskell - 我无法为我的 Forest 数据类型使用这个 Show/Functor 实例

标签 haskell tree instance show functor

我大约两个月前就开始用 Haskell 编程了,我还很新,所以不要指望我能成为 monad 或其他方面的顶级人物。我尝试了很多方法来让这个 Forest 数据类型成为仿函数的实例并显示,但我真的不知道如何解决编译器给我的冲突。如:

    Not in scope: data constructor ‘Tree’
    Perhaps you meant ‘True’ (imported from Prelude)
   |
15 |     show ((Tree a) : (Forest s) ) = "[" ++ show a ++ "," ++ show s ++ "]"
   |            ^^^^

exercici3.hs:15:23: error: Not in scope: data constructor ‘Forest’
   |
15 |     show ((Tree a) : (Forest s) ) = "[" ++ show a ++ "," ++ show s ++ "]"
   |                       ^^^^^^

exercici3.hs:19:12: error:
    Not in scope: data constructor ‘Tree’
    Perhaps you meant ‘True’ (imported from Prelude)
   |
19 |     fmap ((Tree a) : (Forest s)) = [f a] ++ (fmap f s)
   |            ^^^^

exercici3.hs:19:23: error: Not in scope: data constructor ‘Forest’
   |
19 |     fmap ((Tree a) : (Forest s)) = [f a] ++ (fmap f s)
   |                       ^^^^^^

这是类的字体代码。想了很久没有找到合理的解决办法,欢迎大家帮忙,谢谢!


data Tree a = Empty | Node a (Tree a) (Tree a)
data Forest a = Nil  | Cons (Tree a) (Forest a)

instance Show a => Show (Tree a) where
    show Empty = "()"
    show (Node b (xl) (xr)) = "(" ++ show xl ++ "," ++ (show b) ++  "," ++ show xr ++ ")"

instance Functor (Tree ) where
    fmap  f Empty  = Empty
    fmap  f (Node a (xl) (xr)) = Node (f a) (fmap f xl) (fmap f xr)

instance Show a => Show (Forest a) where
    show Nil = []
    show ((Tree a) : (Forest s) ) = "[" ++ show a ++ "," ++ show s ++ "]"

instance Functor (Forest) where
    fmap f Nil = []
    fmap ((Tree a) : (Forest s)) = [f a] ++ (fmap f s)

需要明确的是,Tree 数据类型工作得很好,只是森林的语法部分似乎根本不起作用。

最佳答案

数据构造函数是Cons,而不是(:)。然后,您使用例如 xxs 作为变量,其中 x 的类型为 Tree a,并且 xs 的类型为 Forest a:

instance Show a => Show (Forest a) where
    show Nil = ""
    show (Cons x xs) = "[" ++ show x ++ "," ++ show xs ++ "]"

instance Functor Forest where
    fmap f Nil = Nil
    fmap f (Cons x xs) = Cons (fmap f x) (fmap f xs)

话虽如此,我认为没有太多理由在这里定义数据类型 Forest,您可以将其定义为:

type Forest a = [Tree a]

关于haskell - 我无法为我的 Forest 数据类型使用这个 Show/Functor 实例,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/74246650/

相关文章:

haskell - 如何仅用一个函数解决此数据类型问题,最好使用模式匹配

javascript - 使用 javascript 动态生成树

c - 从字符串生成目录结构

python - 常量实例变量?

haskell - 如何映射和连接文件路径?

Haskell:模板 Haskell 和作用域

Haskell/GHC - "warn incomplete patterns"是否有任何中缀标签/编译指示

c - Merkle 树 - 设置数据并比较结果

.net - 在 .Net 中,如何检查两个标识符是否指向一个对象的同一实例?

android - 将 bool 值放入类型包中的方法不适用于单选按钮