minhajuddin
Using List.first instead of Enum.at(0)
I have seen a lot of code which picks the first element from a list using Enum.at(0) instead of List.first. Is there a reason why people use Enum.at(0)? List.first seems like the simpler of the two.
Most Liked
benwilson512
FWIW I literally never use Enum.at. Lists are the only thing I end up using on a regularly basis where “first” actually means something. That is, I’m not sure why I would ever call Enum.at(0) on a map. Given that looking at a list, List.first is just more semantically clear.
rkma
The difference is that, for an empty list, List.first/1 and Enum.at/2 will return nil and hd and pattern matching will raise an error.
benwilson512
There’s a big difference between hd and List.first however. [] |> hd blows up. [] |> List.first is nil. I almost never use hd because I can generally just pattern match when I expect there will be one thing. List.first is handy when I either want the first thing or nil if there isn’t any.
Popular in Questions
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









