关于递归:在Erlang中传递参数并解析xml

Passing arguments and parsing xml in Erlang

Howdy我仍在学习Erlang,我试图通过函数传递不止一个参数,但我遇到了麻烦。

首先,我使用xmerl.hrl解析xml。我通过命令行使用erlfile:process_xml(" filename.xml ")调用process_xml(Doc)。

1
2
process_xml(Doc) ->
makeBottom1(Doc,"yup got here").

从此处开始,过程调用makeBottom1传递文档和一个字符串以稍后测试输出。

1
2
makeBottom1(E = #xmlElement{name='resource'}, Derp) ->"Got to resource";
makeBottom1(E, Derp) -> ["BURP", Derp, built_in_rules( fun makeBottom1/2 , [E, Derp] ),"-" ].

我希望它返回" Got to resource "的次数,但似乎永远不会触发该函数调用。

它返回的内容是:

1
["BURP","yup got here",[],"-"]

我应该为我想要的功能使用其他xml解析器吗?我只是在犯一个菜鸟错误吗?


函数built_in_rules需要2个参数:具有Arity 1(一个参数)的函数和一个XML节点。由于您的参数不符合function子句描述的模式,因此您将触发一个包罗万象的条件,该条件只会返回一个空列表。

要变通解决此问题,您需要更改使用built_in_rules的方式。请尝试以下操作:

1
built_in_rules(fun(Child) -> makeBottom1(Child, Derp) end, E)

我们没有尝试传入Arity为2的函数并期望built_in_rules知道如何处理它,而是传入Arity为1的函数,而built_in_rules确切地知道如何使用它,并使用一个闭包以添加我们的第二个参数。我们还将第二个参数修改为函数调用,以便仅传递当前的XML节点。