这是我的 ADT:
data Tree a = Val Integer
|Tree a
|Variable a
我有两个问题:
问题一:用Tree String类型来表示一些树?
问题2:定义一个函数,用于将树,数据类型Tree String的元素转换为字符串:showTree::Tree String -> String
这是我的 ADT:
data Tree a = Val Integer
|Tree a
|Variable a
我有两个问题:
问题一:用Tree String类型来表示一些树?
问题2:定义一个函数,用于将树,数据类型Tree String的元素转换为字符串:showTree::Tree String -> String
关于您的第二个问题,将树转换为字符串,只需派生Show
并使用该show
函数:
data Tree a = Val Integer
| Tree a
| Variable a
deriving (Eq, Ord, Show)
showTree :: (Show a) => Tree a -> String
showTree = show
我不明白你的第一个问题,所以我只想谈谈,希望我所说的对你有所帮助。
了解您的“树”数据类型根本不是真正的树,它只是一个 sum 数据类型,可以通过整数或与类型变量匹配的某种类型来实例化,a
. 第二个构造函数,Tree
实际上并没有使您的数据类型递归 - 它只是一个构造函数名称,就像构造函数Variable
名称一样。我认为您可能想要拥有子树(通过Tree
用作类型,而不是构造函数) - 所以让我们将您的类型定义为:
data Tree a = Val Integer
| Branch (Tree a) (Tree a)
| Variable a
现在你有一个名为的构造函数Branch
,它有一个左子树和一个右子树。如果你的变量应该是String
s 那么你当然可以用它Tree String
来表示:
myTree :: Tree String
myTree =
let leftBranch = Variable "x"
rightBranch = Branch (Val 3) (Variable "y")
in Branch leftBranch rightBranch