有两个明显的方法可以构建数学链表,“左”:左VS右链表,替换速度
{1, {2, {3, {4, {5, {6, {7, {}}}}}}}}
和“右”:
{{{{{{{{}, 7}, 6}, 5}, 4}, 3}, 2}, 1}
这些都可以
toLeftLL = Fold[{#2, #} &, {}, [email protected]#] & ;
toRightLL = Fold[List, {}, [email protected]#] & ;
如果我使用这些,并做了简单的ReplaceRepeated
通过链表走,我得到drasti:与制造cally不同Timing
结果:
r = Range[15000];
left = [email protected];
right = [email protected];
Timing[i = 0; left //. {head_, tail_} :> (i++; tail); i]
Timing[i = 0; right //. {tail_, head_} :> (i++; tail); i]
(* Out[6]= {0.016, 15000} *)
(* Out[7]= {5.437, 15000} *)
为什么?
我想这可能是因为尾部调用优化速度更快。 – Andrey 2011-04-27 00:29:32
选择这个:http://stackoverflow.com/questions/4481301/tail-call-optimization-in-mathematica – Andrey 2011-04-27 00:33:49
@Mr。向导:你可以分解你的'RuleDelayed'的RHS。虽然我觉得我可以看到它是如何遍历列表的,但这并不完全清楚。另外,如果我用尾巴+ tail替换RHS中的'tail',我得到一个错误:'$ RecursionLimit :: reclim:超过256的递归深度。 >>'并且需要中止。为什么没有找到“tail-tail + tail = tail”并返回与以前相同的结果? – abcd 2011-04-27 01:44:16