问题
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 tailTail
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