Reverse concat in Elixir

◇◆丶佛笑我妖孽 提交于 2019-12-11 12:56:49

问题


Is there a standard library function in Elixir (or Erlang) to concatenate the reverse of a list in front of some other list? Basically I'm looking for an equivalent of reverse_::: in Scala.

The rationale is that it's handy when implementing a tail-recursive algorithm on a list. During recursion, you hold on to some of the elements for later by adding them onto the front of an accumulator list. In the end you can reverse-concat them onto the remainder of the assembled list in one go (which should be pretty efficient).


回答1:


You can do a reverse and concat in Erlang by using lists:reverse/2.

I think the documentation explanation and example are clear enough:

reverse(List1, Tail) -> List2.

Returns a list with the elements in List1 in reverse order, with the tail Tail appended.

> lists:reverse([1, 2, 3, 4], [a, b, c]).
[4,3,2,1,a,b,c]



回答2:


The function to reverse a list in Elixir is Enum.reverse/1, and Enum.reverse/2 can be used to reverse and concatenate:

iex> Enum.reverse([1,2,3])
[3, 2, 1]
iex> Enum.reverse([1,2,3], [:a, :b, :c])
[3, 2, 1, :a, :b, :c]


来源:https://stackoverflow.com/questions/37777787/reverse-concat-in-elixir

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!