在以下代码中使用 toString1 选择正确类型的 MyTreeInt 确定:
-- ***************
-- * MODULE Main *
-- ***************
module Main( main ) where
-- **********
-- * MyTree *
-- **********
data MyTree
= MyTreeInt
| MyTreeString
-- *************
-- * MyTreeInt *
-- *************
data MyTreeInt
= MyTreeIntAtom Int
| MyTreeIntPlus MyTreeInt MyTreeInt
| MyTreeIntMinus MyTreeInt MyTreeInt
-- ****************
-- * MyTreeString *
-- ****************
data MyTreeString
= MyTreeStringAtom String
| MyTreeStringConcat String String
-- *************
-- * toString1 *
-- *************
toString1 :: MyTreeInt -> String
toString1 (MyTreeIntAtom i) = "PPPPP"
toString1 (MyTreeIntPlus t1 t2) = "QQQQQ"
-- *************
-- * toString2 *
-- *************
-- toString2 :: MyTree -> String
-- toString2 (MyTreeIntAtom i) = "RRRRR"
-- toString2 (MyTreeIntPlus t1 t2) = "SSSSS"
-- ********
-- * main *
-- ********
main :: IO ()
main = do putStrLn (toString1 (MyTreeIntAtom 8))
但是,当类型层次结构大于1时, 比如 MyTree ,是否可以将 toString2 写入 处理所有 int和字符串树? 提前致谢
答案 0 :(得分:3)
此类型
data MyTree
= MyTreeInt
| MyTreeString
与类型MyTreeInt
和MyTreeString
完全无关。上面,这些名称用作数据构造函数名称,而不是类型名称,因此它们不引用其他树类型。你可能想要像
data MyTree
= MyTreeInt MyTreeInt
| MyTreeString MyTreeString
其中,在构造函数名称之后,我们还包括树的类型。
然后,我们可以写
toString2 :: MyTree -> String
toString2 (MyTreeInt (MyTreeIntAtom i)) = "A"
toString2 (MyTreeInt (MyTreeIntPlus t1 t2)) = "B"
toString2 (MyTreeString (MyTreeStringAtom i)) = "C"
toString2 (MyTreeString (MyTreeStringConcat t1 t2)) = "D"
我们也可以重复使用辅助功能,例如
toString2 :: MyTree -> String
toString2 (MyTreeInt t) = treeIntToString t -- this is toString1
toString2 (MyTreeString t) = treeStringToString t -- this has to be defined