有兩個明顯的方法可以構建數學鏈表,「左」:左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