How would you simply remove 20 from the end of this example?
[46, 238, 64, 30, 105, 136, 98, 75, 23, 157, 11, 20]
How would you simply remove 20 from the end of this example?
[46, 238, 64, 30, 105, 136, 98, 75, 23, 157, 11, 20]
fastest solution that I know of with @mudasobwa's one
solution 1:
x |> Enum.reverse() |> tl() |> Enum.reverse()
Some other solutions:
solution 2:
[k] = Enum.chunk(x, length(x)-1)
solution 3:
List.delete_at(x, length(x)-1)
solution 4:
x |> List.to_tuple() |> Tuple.delete_at(length(x)-1) |> Tuple.to_list
An even more interesting question, is how to do that the fastest way ? let's benchmark it !
I got the following result using Benchee, each solution was computed 50000 times, and I used a list created with Enum.to_list(1..10_000)
Name ips average deviation median 99th %
mudasobwa's solution 14.80 K 67.57 μs ±34.17% 79 μs 91 μs
solution 1 14.79 K 67.59 μs ±33.96% 79 μs 91 μs
solution 4 10.71 K 93.38 μs ±32.67% 81 μs 201 μs
Roman Rabinovich's solution 8.45 K 118.33 μs ±18.27% 118 μs 171 μs
OneSneakyMofo's solution 5.07 K 197.34 μs ±13.60% 193 μs 331 μs
dawner's solution 4.57 K 219.00 μs ±11.87% 216 μs 256.23 μs
solution 3 3.41 K 292.91 μs ±20.01% 290 μs 506.64 μs
solution 2 0.83 K 1205.52 μs ±22.25% 1105 μs 2061.77 μs
Comparison:
mudasobwa's solution 14.80 K
solution 1 14.79 K - 1.00x slower
solution 4 10.71 K - 1.38x slower
Roman Rabinovich's solution 8.45 K - 1.75x slower
OneSneakyMofo's solution 5.07 K - 2.92x slower
dawner's solution 4.57 K - 3.24x slower
solution 3 3.41 K - 4.33x slower
solution 2 0.83 K - 17.84x slower
You could do:
List.pop_at(x, -1)
{20, [46, 238, 64, 30, 105, 136, 98, 75, 23, 157, 11]}
So many ways to do this. Here's another:
[46, 238, 64, 30, 105, 136, 98, 75, 23, 157, 11, 20]
|> Enum.reject(&(&1 == 20)
While the solution given by Nathan Ripert is good enough, it’s not exactly fastest.
Enum.reverse/1 is a general-purpose function that goes through reduce.
Pure erlang :lists.reverse/1 should be faster (very very slightly):
x |> :lists.reverse(x) |> tl() |> :lists.reverse()