如何将二叉树的字符串表示读回树中?
How to read a string representation of a binary tree back into the tree?
我有以下代码接受输入作为 ex
中给出的示例并创建具有给定类型的树:
data QA = Leaf String | Question QA String QA
ex :: QA
ex = (Question
(Question (Leaf "Marie Curie") "Is she a scientist?" (Leaf "Queen Elisabeth II"))
"Is she from Europe?"
(Question (Leaf "Marilyn Monroe") "Is she an actress?" (Leaf "Hilary Clinton")))
showQa :: QA -> String
showQa (Leaf x) = "(" ++ x ++ ")"
showQa (Question left x right) = "(" ++ x ++ showQa left ++ showQa right ++ ")"
instance Show QA where
show = showQa
然后我使用 showQa 函数将树转换为字符串,以便能够将其存储在文件中,并以字符串形式输出以下内容:
"(Is she from Europe?(Is she a scientist?(Marie Curie)(Queen Elisabeth II))(Is she an actress?(Marilyn Monroe)(Hilary Clinton)))"
问题是当我再次从文件中读取字符串时,如何将这个字符串转换为原始类型的原始树。
使 QA 成为展示和阅读的实例
data QA = Leaf String | Question QA String QA deriving (Show, Read)
您可以通过这种方式摆脱 showQa,只调用 QA 类型上的 show。读书也一样。
在写入文件时您可以
writeFile "[FileName].qa" (show ex)
“ex”应该是 QA 类型的名称,在您的情况下它被称为 ex
从文件中读取你可以只使用 readFile 并读取结果:
fileReader = do
content <- tryIOError (readFile "[FileName].qa")
case content of
Left e -> do
return (ex) --In case of reading file goes wrong
Right r -> do
return (read r)
我有以下代码接受输入作为 ex
中给出的示例并创建具有给定类型的树:
data QA = Leaf String | Question QA String QA
ex :: QA
ex = (Question
(Question (Leaf "Marie Curie") "Is she a scientist?" (Leaf "Queen Elisabeth II"))
"Is she from Europe?"
(Question (Leaf "Marilyn Monroe") "Is she an actress?" (Leaf "Hilary Clinton")))
showQa :: QA -> String
showQa (Leaf x) = "(" ++ x ++ ")"
showQa (Question left x right) = "(" ++ x ++ showQa left ++ showQa right ++ ")"
instance Show QA where
show = showQa
然后我使用 showQa 函数将树转换为字符串,以便能够将其存储在文件中,并以字符串形式输出以下内容:
"(Is she from Europe?(Is she a scientist?(Marie Curie)(Queen Elisabeth II))(Is she an actress?(Marilyn Monroe)(Hilary Clinton)))"
问题是当我再次从文件中读取字符串时,如何将这个字符串转换为原始类型的原始树。
使 QA 成为展示和阅读的实例
data QA = Leaf String | Question QA String QA deriving (Show, Read)
您可以通过这种方式摆脱 showQa,只调用 QA 类型上的 show。读书也一样。
在写入文件时您可以
writeFile "[FileName].qa" (show ex)
“ex”应该是 QA 类型的名称,在您的情况下它被称为 ex
从文件中读取你可以只使用 readFile 并读取结果:
fileReader = do
content <- tryIOError (readFile "[FileName].qa")
case content of
Left e -> do
return (ex) --In case of reading file goes wrong
Right r -> do
return (read r)