gpt4 book ai didi

go - 找到元素时停止递归函数

转载 作者:IT王子 更新时间:2023-10-29 02:15:08 24 4
gpt4 key购买 nike

我正在尝试解决 The go programming language book 中的一个练习:起始代码可以在这里找到:exercise .

我需要做的:

修改forEachNode,让pre和post函数返回一个boolean结果,表示是否继续遍历。使用它编写具有以下签名的 ElementByID 函数,该函数可查找具有指定 id 属性的第一个 HTML 元素。该函数应在找到匹配项后立即停止遍历。

签名:func ElementByID(doc *html.Node, id string) *html.Node

我做了什么:

func ElementByID(doc *html.Node, id string) *html.Node {                                                         
if doc.Data == id {
fmt.Printf(" %s: %s\n", "found", doc.Data)
return doc
}
return nil
}

func startElement(n *html.Node) bool {
if n.Type == html.ElementNode {
if ElementById(n, "a") != nil {
return true
}
fmt.Printf("%*s<%s>\n", depth*2, "", n.Data)
depth++
}
return false
}
func endElement(n *html.Node) bool {
if n.Type == html.ElementNode {
if ElementById(n, "a") != nil {
return true
}
depth--
fmt.Printf("%*s</%s>\n", depth*2, "", n.Data)
}
return false
}

以上是正确的吗?还是我漏掉了什么?如何停止找到元素的遍历?

forEachNode 相同,只是前后签名更改为返回 bool。

最佳答案

您可以创建一个 closure并“关闭”found 节点。示例如下。

Modify forEachNode so that the pre and post functions return a boolean result indicating whether to continue the traversal.:

func forEachNode(n *html.Node, pre, post func(n *html.Node) bool) {
if pre != nil && !pre(n) {
return
}

for c := n.FirstChild; c != nil; c = c.NextSibling {
forEachNode(c, pre, post)
}

if post != nil && !post(n) {
return
}
}

Use it to write a function ElementByID with the following signature that finds the first HTML element with the specified id attribute. The function should stop the traversal as soon as a match is found.:

func ElementByID(doc *html.Node, id string) *html.Node {

var found *html.Node

pre := func(n *html.Node) bool {
for _, a := range n.Attr {
if a.Key == "id" && a.Val == id {
found = n // memorize matching node
return false // stop traversing
}
}
return true
}

forEachNode(doc, pre, nil)
return found
}

关于go - 找到元素时停止递归函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34694295/

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