Reputation: 3051
In Haskell the init
function returns all the elements in a list except the last element.
For example init [1, 2, 3]
would return [1, 2]
.
Is there a similar function in Elixir?
I can't find any similar function in the Enum
or List
module.
Upvotes: 3
Views: 289
Reputation: 2473
It's always nice to confirm suspicions in these situations, so here's a benchmark comparing the two:
Settings:
duration: 1.0 s
## ListBench
[13:29:22] 1/2: Enum.drop(-1)
[13:29:26] 2/2: Enum.slice(0..-2)
Finished in 7.41 seconds
## ListBench
benchmark name iterations average time
Enum.drop(-1) 50000 72.32 µs/op
Enum.slice(0..-2) 10000 273.16 µs/op
So yes, Enum.drop
is the preferred option.
Upvotes: 1
Reputation: 9079
If you like you can also use Enum.drop/2, which Drops the first count items from the collection. If a negative value count is given, the last count values will be dropped.
[1,2,3] |> Enum.drop(-1) # [1,2]
Upvotes: 8
Reputation: 84140
You can do this with Enum.slice/2 providing a decreasing range with a negative end:
[1, 2, 3] |> Enum.slice(0..-2) # [1, 2]
Upvotes: 4