elixir - how to get all elements except last in th

2020-04-02 01:22发布

问题:

Let say I have a list [1, 2, 3, 4]

How can I get all elements from this list except last? So, I'll have [1, 2, 3]

回答1:

Use Enum.drop/2 like this:

list = [1, 2, 3, 4]
Enum.drop list, -1      # [1, 2, 3]


回答2:

My solution (I think it's not a clean, but it works!)

a = [1, 2, 3, 4]
[head | tail] = Enum.reverse(a)
Enum.reverse(tail) # [1, 2, 3]


回答3:

If you're looking to get both the last item and the rest of the list preceding it you can now use List.pop_at/3:

{last, rest} = List.pop_at([1, 2, 3], -1)
{3, [1, 2]}

https://hexdocs.pm/elixir/List.html#pop_at/3



回答4:

Another option besides the list |> Enum.reverse |> tl |> Enum.reverse mentioned before is Erlang's :lists.droplast function which is slower according to the documentation but creates less garbage because it doesn't create two new lists. Depending on your use case that might be an interesting one to use.



回答5:

Another option, though not elegant, would be -

list = [1, 2, 3, 4]
Enum.take(list, Enum.count(list) -1 )   # [1, 2, 3]


回答6:

Erlang

List = [1,2,3,4,5],
NewList = DropLast(List).

DropLast(List) while length(List) > 0 and is_list(List) ->
    {NewList, _} = lists:split(OldList, length(OldList)-1),
    NewList.


标签: elixir