【问题标题】:How to read a string representation of a binary tree back into the tree?如何将二叉树的字符串表示读回树中?
【发布时间】:2022-03-16 02:00:53
【问题描述】:

我有以下代码接受输入作为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)))"

问题是当我再次从文件中读取字符串时,如何将此字符串转换为具有原始类型的原始树。

【问题讨论】:

  • 你对解析了解多少?这是解析以前缀顺序序列化的二叉树的非常简单的应用程序,这几乎是解析为递归数据结构的最简单的情况。没有任何大的挑战,但值得了解您对哪些相关想法感到满意。
  • 当然……这种序列化格式很难反转,因为它允许在字符串中使用任意括号。这允许模棱两可的形式,其中多个输入序列化为相同的输出,这就是......好吧,这是反转操作的问题。
  • 你关心你的文本格式的细节吗? data QA = Leaf String | Question QA String QA deriving (Eq, Show, Read) 有什么问题

标签: haskell functional-programming tree binary-tree


【解决方案1】:

让 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)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2012-11-06
    • 2021-11-23
    • 1970-01-01
    • 2022-01-03
    • 2022-01-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多