我的Google Reader分享

Monday, November 03, 2008

Programming Erlang 笔记(四)

Building Lists in Natural Order

The most efficient way to build a list is to add the elements to the head of an existing list────构建一个列表的最有效率的方法是在一个把元素加到一个已有的列表头上(head)。

常见的代码:

some_function([H|T], ..., Result, ...) ->
H1 = ... H ...,
some_function(T, ..., [H1|Result], ...);
some_function([], ..., Result, ...) ->
{..., Result, ...}.


This code walks down a list extracting the head of the list H and computing some value based on this function (we can call this H1); it then adds H1 to the output list Result.────这段代码不断的取出列表H的头(head),然后根据H1这个函数计算它的值;再把它加到输出列表Result的头上。

The basic idea is fairly simple:
1. Always add elements to a list head.
2. Taking the elements from the head of an InputList and adding them head first to an OutputList results in the OutputList having the reverse order of the InputList.
3. If the order matters, then call lists:reverse/1, which is highly optimized.
4. Avoid going against these recommendations.

最基本的思想相当简单:
1.总是把元素加到列表的头上;
2.从输入列表的头上取元素,把元素加到输出列表的头上,这样输出列表中元素顺序和输入列表正好相反;
3.如果顺序对你有影响,调用list:reverse/1,它是高度优化过的;
4.避免违反这几条。

If you ever see code like this:
List ++ [H]
it should set alarm bells off in your brain—this is very inefficient and acceptable only if List is very short.

如果你看到这样的代码
List ++ [H]
你的脑子应该敲响警钟了────这是非常没有效率的而且只能在列表很短的时候才能接受。


Accumulators (我不明白为什么叫这个名字,蓄电池?)

odds_and_evens(L) ->
Odds = [X || X <- L, (X rem 2) =:= 1],
Evens = [X || X <- L, (X rem 2) =:= 0],
{Odds, Evens}.
5> lib_misc:odds_and_evens([1,2,3,4,5,6]).
{[1,3,5],[2,4,6]}


这个要两次遍历

odds_and_evens_acc(L) ->
odds_and_evens_acc(L, [], []).
odds_and_evens_acc([H|T], Odds, Evens) ->
case (H rem 2) of
1 -> odds_and_evens_acc(T, [H|Odds], Evens);
0 -> odds_and_evens_acc(T, Odds, [H|Evens])
end;
odds_and_evens_acc([], Odds, Evens) ->
{Odds, Evens}.


这个只要一次遍历

No comments: