我大约两个月前就开始用 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
,而不是(:)
。然后,您使用例如 x
和 xs
作为变量,其中 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/