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.
sotojuan
I just use hd.
alexgaribay
The docs for the List module states it works only on lists whereas the Enum module works on anything that implements the Enumerable protocol. Additionally, the List module docs recommends using the Enum module.
This comes directly from the List docs:
Specialized functions that only work on lists.
In general, favor using the Enum API instead of List.
I’d probably go with using Enum in general. I have never found myself reaching for an API available in List in the past year of my Elixir development.







