Reverse concat in Elixir

2019-07-30 22:36发布

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).

2条回答
叛逆
2楼-- · 2019-07-30 22:55

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]
查看更多
老娘就宠你
3楼-- · 2019-07-30 23:08

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]
查看更多
登录 后发表回答