gpt4 book ai didi

haskell - 用于图形库的 xml-tree 解析器 (Haskell)

转载 作者:行者123 更新时间:2023-12-04 06:29:26 25 4
gpt4 key购买 nike

我正在编写一个用于处理图形的库。
主要任务 - 解析 xml-tree。
树看起来像

<graph nodes=4 arcs=5>
<node id=1 />
<node id=2 />
<node id=3 />
<node id=4 />
<arc from=1 to=2 />
<arc from=1 to=3 />
<arc from=1 to=4 />
<arc from=2 to=4 />
<arc from=3 to=4 />
</graph>

存储结构:
type Id = Int

data Node = Node Id deriving (Show)
data Arc = Arc Id Id deriving (Show)

data Graph = Graph { nodes :: [Node],
arcs :: [Arc]}

如何将xml文件中的数据写入这个结构?
我无法为这种 xml 树编写解析器(HXT 库)

最佳答案

假设您将其转换为正确的 XML(用引号将所有属性值括起来),以下代码将起作用(使用 xml-enumerator):

{-# LANGUAGE OverloadedStrings #-}
import Text.XML.Enumerator.Parse
import Control.Monad
import Data.Text (unpack)
import Control.Applicative

type Id = Int

data Node = Node Id deriving (Show)
data Arc = Arc Id Id deriving (Show)

data Graph = Graph { nodes :: [Node],
arcs :: [Arc]}
deriving Show

main = parseFile_ "graph.xml" decodeEntities $ force "graph required" parseGraph

parseGraph = tagName "graph" getCounts $ \(nodeCount, arcCount) -> do
nodes <- replicateM nodeCount parseNode
arcs <- replicateM arcCount parseArc
return $ Graph nodes arcs
where
requireNum name = do
x <- requireAttr name
case reads $ unpack x of
(i, _):_ -> return i
_ -> fail $ "Invalid integer: " ++ unpack x
getCounts = do
n <- requireNum "nodes"
a <- requireNum "arcs"
return (n, a)
parseNode = force "node required" $ tagName "node"
(Node <$> requireNum "id") return
parseArc = force "arc required" $ tagName "arc"
(Arc <$> requireNum "from" <*> requireNum "to") return

输出:
Graph {nodes = [Node 1,Node 2,Node 3,Node 4], arcs = [Arc 1 2,Arc 1 3,Arc 1 4,Arc 2 4,Arc 3 4]}

关于haskell - 用于图形库的 xml-tree 解析器 (Haskell),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5622238/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com