我有以下代码,它接受输入作为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)))"问题是,当我再次从文件中读取字符串时,如何将这个字符串转换为原始类型的树。
发布于 2022-03-15 18:00:53
使QA成为显示和读取的实例
data QA = Leaf String | Question QA String QA deriving (Show, Read)您可以通过这种方式摆脱showQa,只需调用QA类型的显示即可。读书也是如此。
当你写到文件时你可以
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)https://stackoverflow.com/questions/69730321
复制相似问题