Haskell,如何将ADT转换为String?

Sam*_*Sam -3 haskell functional-programming

这是我的ADT:

data Tree a = Val Integer
            |Tree a
            |Variable a
Run Code Online (Sandbox Code Playgroud)

我有两个问题:

问题1:使用Tree String类型来表示一些树?

问题2:定义一个函数,用于将树,数据类型Tree String的元素转换为字符串:showTree :: Tree String - > String

Tho*_*son 5

关于你的第二个问题,将树转换为字符串,只需派生Show并使用该show函数:

data Tree a = Val Integer
            | Tree a
            | Variable a
    deriving (Eq, Ord, Show)

showTree :: (Show a) => Tree a -> String
showTree = show
Run Code Online (Sandbox Code Playgroud)

我不明白你的第一个问题,所以我只想谈一点,希望我说的话可以帮到你.

理解你的"树"数据类型根本不是一棵树,它只是一个sum数据类型,可以通过整数或某种与类型变量匹配的类型来实例化a.第二个构造函数,Tree实际上并没有使您的数据类型递归 - 它只是一个构造函数名称,以相同的方式Variable是构造函数名称.我想你可能想要使用子树(通过使用Tree作为类型,而不是构造函数) - 所以让我们将你的类型定义为:

data Tree a = Val Integer
            | Branch (Tree a) (Tree a)
            | Variable a
Run Code Online (Sandbox Code Playgroud)

现在,您有一个名为Branch左侧和右侧子树的构造函数.如果您的变量应该是Strings,那么您当然可以用它Tree String来表示:

myTree :: Tree String
myTree =
    let leftBranch = Variable "x"
        rightBranch = Branch (Val 3) (Variable "y")
    in Branch leftBranch rightBranch
Run Code Online (Sandbox Code Playgroud)