Hello,
Could anyone provide a more idiomatic Elixir explanation of the behavior of Enum.map/2 in the following expression, particularly regarding how it handles an empty list?
iex(2)> Enum.map([], fn (2) -> 2+ 2 end)
[]
iex(3)> Enum.map([2], fn (2) -> 2+ 2 end)
[4]
Thanks! 
Enum.map with a list as the first argument just swaps the arguments and calls :lists.map:
https://github.com/elixir-lang/elixir/blob/47abe2d107e654ccede845356773bcf6e11ef7cb/lib/elixir/lib/enum.ex#L1702-L1704
:lists.map has a guard that checks the arity of the supplied function, but the body of the function doesn’t call it if the list is empty:
https://github.com/erlang/otp/blob/90a48ae2bff26d5df67ceaa7e96971967c33ea8a/lib/stdlib/src/lists.erl#L2075-L2079
fn (2) -> 2 + 2 end is still an arity-1 function, it just happens to crash for any value of that single argument besides 2.
@stevegee1 welcome!
Hopefully, @al2o3cr answered your question. If not, perhaps you can explain how you are confused or what you expected Enum.map/2 to do?
Try changing the list to [3].
Thanks! @al2o3cr @jswanner for the swift reply. My question has been duly answered with this:
The body of the function doesn’t call it if the list is empty.
Yes, it crashes. I was only confused about its behavior with an empty list until now.
Thanks @dimitarvp