Recursion 复杂的递归堆栈效应?
上述代码将在维基百科上的每个链接上递归,直到找到它要查找的链接为止 这没关系,因为(希望)Recursion 复杂的递归堆栈效应?,recursion,tail-recursion,factor-lang,Recursion,Tail Recursion,Factor Lang,上述代码将在维基百科上的每个链接上递归,直到找到它要查找的链接为止 这没关系,因为(希望)findpath最终将“返回”(即不再调用自身),并在堆栈上留下一个巨大的嵌套数据结构。但是当我试图编译这个时,我得到了一个错误: 递归单词“findpath”离开时堆栈的高度错误 不平衡递归:当堆栈效果推断确定内联递归字具有不正确的堆栈效果声明时引发 不管我做什么,Factor(可以理解)抱怨堆栈效应不匹配。我必须做些什么才能使它正确地递归?仔细查看查找路径单词。我将添加注释,以便您可以查看堆栈上的内容:
findpath
最终将“返回”(即不再调用自身),并在堆栈上留下一个巨大的嵌套数据结构。但是当我试图编译这个时,我得到了一个错误:
递归单词“findpath”离开时堆栈的高度错误
不平衡递归
:当堆栈效果推断确定内联递归字具有不正确的堆栈效果声明时引发
不管我做什么,Factor(可以理解)抱怨堆栈效应不匹配。我必须做些什么才能使它正确地递归?仔细查看
查找路径
单词。我将添加注释,以便您可以查看堆栈上的内容:
USING: accessors html.parser.analyzer io kernel math namespaces
present regexp sequences ;
IN: all-roads-to-wiki
SYMBOL: G
: match-good-pages ( a -- ?/f )
R/ \/wiki\/[^:]*$/ first-match ;
: filter-urls ( tags -- urls )
find-hrefs [ present ] map
[ match-good-pages ] filter
[ match-good-pages seq>> ] map ;
: findpath ( url -- url )
G get =
[
! false
]
[ scrape-html nip
[
dup "title" find-by-name drop 1 + swap nth
text>> R/ - Wikipedia,/ re-split first print
]
[
"bodyContent" find-by-id-between filter-urls [ findpath ] map
] bi
] if ; inline recursive
: allroads-entry ( -- a )
readln "http://en.wikipedia.org/wiki/" prepend G set-global
"enwp.org/Special:Random" findpath ; inline
if
组合器消耗堆栈上的最后一项,因此此代码可能无法工作。以下是findpath
word的工作代码:
: findpath ( url -- url )
! 1 item: { url }
G
! 2 items: { url G }
get
! 2 items: { url value-of-G }
=
! 1: item { t/f }
[
! 0 items!!!!
! false
]
[ scrape-html nip
[
dup "title" find-by-name drop 1 + swap nth
text>> R/ - Wikipedia,/ re-split first print
]
[
"bodyContent" find-by-id-between filter-urls
[ findpath ] map
] bi
] if ; inline recursive
另外,请查看用于此类任务的。如果我理解正确,请在false分支中删除f,并筛选以删除列表中的false。2-我认为它在
G get=
之前缺少了一个dup
(因为=使用url)。3-你确定递归结束了吗?这个列表不会永远保持增长吗?这不就像是对链接图的深度优先搜索吗?如果你在某个地方找到了一个循环,你将永远被困在那里@联邦快递。您可能是对的,但它应该像递归解决方案一样工作:
: page-title ( seq -- title )
dup "title" find-by-name drop 1 + swap nth
text>> R/ - Wikipedia,/ re-split first ;
: page-links ( seq -- links )
"bodyContent" find-by-id-between filter-urls ;
: scrape-en-wiki-url ( wiki-url -- seq )
"https://en.wikipedia.org" prepend
dup print flush scrape-html nip ;
: found-url? ( wiki-url -- ? )
G get [ = ] [ drop t ] if* ;
: findpath ( wiki-url -- seq/f )
dup found-url?
[ drop f G set f ] [
scrape-en-wiki-url
[ page-title print flush ] [
page-links [ findpath ] map
] bi
] if ; inline recursive