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.
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]
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]
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With