Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there an equivalent to Haskell's init function in elixir?

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.

like image 359
Chedy2149 Avatar asked Mar 10 '26 15:03

Chedy2149


2 Answers

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]
like image 56
coderVishal Avatar answered Mar 12 '26 15:03

coderVishal


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]
like image 40
Gazler Avatar answered Mar 12 '26 16:03

Gazler