CharlesO
Shouldn't we have a List.nth in Elixir?
Erlang :list.nth simple, but 1 - based
nth(1, [H|_]) -> H;
nth(N, [_|T]) when N > 1 ->
nth(N - 1, T).
Elixir Enum.at … cool, but not focused on Lists
def at(enumerable, index, default \\ nil) do
case fetch(enumerable, index) do
{:ok, h} -> h
:error -> default
end
end
...
# other code to check if _is a list_ or not, before redirtecting to do_fetch...
Elixir could (should?) have List.nth, a 0-based equivalent of Erlang’s :list.nth that expects to work only on lists (nth could even make it into the kernel
)
Most Liked
michalmuskala
I have no idea why this discussion continues, and where is the confusion. I have no idea where do you expect it to lead by arguing about 0-based and 1-based indexation.
Elixir uses 0-based indexation everywhere. That’s it. There is no confusion what Enum.at(4) returns - the item with index 4, which is the fifth element of the collection.
As I stated in the first post, there’s entirely no reason to introduce List.nth/2 since this is completely covered by Enum.at/2. The performance is also exactly the same for both, as both use exactly the same code when executed on lists. It makes no point to introduce a 1-based list access when access everywhere in elixir, to all indexed structures is 0-based.
Please let’s stop this discussion if there’s nothing constructive to add.
michalmuskala
The Enum,fetch/2 that Enum.at/2 uses has a clause that is specialised for lists, so it should be as efficient as the Erlang’s :lists.nth/2 without introducing extra functions.
https://github.com/elixir-lang/elixir/blob/master/lib/elixir/lib/enum.ex#L2773-L2778
NobbZ
Also nomenclature forbids zero basing nth. There is no element before the first.
Popular in Discussions
Other popular topics
Categories:
Sub Categories:
Forums
Popular Tags
- #ecto
- #liveview
- #troubleshooting
- #learning-elixir
- #deployment
- #library
- #erlang
- #testing
- #genserver
- #mix
- #absinthe
- #remote-other
- #otp
- #plug
- #how-to-question
- #macros
- #postgres
- #channels
- #elixirconf
- #exunit
- #discussion
- #code-sync
- #javascript
- #podcasts
- #onsite
- #dialyzer
- #docker
- #authentication
- #umbrella
- #full-time-contract
- #podcasts-by-brainlid
- #ecto-query
- #elixir-ls
- #phoenix_html
- #iex
- #blog-post
- #graphql
- #genstage
- #ai
- #websockets
- #supervisor
- #advent-of-code
- #elixirconf-us
- #distillery
- #processes
- #forms
- #api
- #metaprogramming
- #security
- #performance








