简体   繁体   中英

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.

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]

您可以使用Enum.slice / 2执行此操作,提供具有负端的递减范围

[1, 2, 3] |> Enum.slice(0..-2) # [1, 2]

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM