>> proc e -> do key1 -6ren">
gpt4 book ai didi

haskell - 更好地使用 HXT 和箭头

转载 作者:行者123 更新时间:2023-12-02 00:25:03 28 4
gpt4 key购买 nike

我一直在使用 hxt 没有问题,但从一开始就有问题。看,想象一下下面的一段代码

liftKeys = atTag "myKeys" >>>
proc e -> do
key1 <- getAttrValue "name" -< e
key2 <- getAttrValue "chance" -< e
returnA -< (key1, key2)

我已经像那样使用它来解析许多文档,并且在经典的编程问题之前,缺乏抽象。

<zone id= "greenhill">
<key name="a" chance = "10" />
<key name="v" chance = "10"/>
</zone>

我有四个(还有更多)文件要像这个例子一样解析。有些有 2 个属性,有些有 5 个,有些有 1 个等我不能根据我的文件具有的属性数量编写不同版本的 liftKeys。问题是我真的不明白箭头或者我在做什么必须有一些折叠或其他东西才能编写更简单的代码。

你知道更好的用法吗?

最佳答案

如果您有不同数量的属性,那么从属性名称列表构造箭头似乎是最自然的解决方案。然而,要做到这一点,我们将需要一个小的辅助函数来将箭头列表转换为生成列表的单个箭头。

arrowList :: Arrow a => [a b c] -> a b [c]
arrowList [] = arr $ const []
arrowList (a:arrows) = proc b -> do
c <- a -< b
cs <- arrowList arrows -< b
returnA -< (c:cs)

可能类似这样的东西已经存在于某些箭头实用程序库中,但我无法通过快速搜索找到一个。在这里,给定一个箭头列表 [a b c],我们首先将 b 馈送到第一个箭头,然后递归地合并列表的其余部分,然后将它们合并为一个箭头将 b 喂给那个合并的箭头。

为了便于解释,我使用箭头符号编写了上述函数,但您可以像这样简单地实现它:

arrowList :: Arrow a => [a b c] -> a b [c]
arrowList [] = arr $ const []
arrowList (a:arrows) = a &&& arrowList arrows >>> arr (uncurry (:))

现在我们可以像这样实现liftKeys函数

liftKeys :: ArrowXml a => [String] -> a XmlTree [String]
liftKeys keys = atTag "myKeys" >>> arrowList (map getAttrValue keys)

您上面的原始示例可以表示为 liftKeys ["name", "chance"]

关于haskell - 更好地使用 HXT 和箭头,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9137647/

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