Enum.map/2 behaviour on empty list

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! :smiley:

Enum.map with a list as the first argument just swaps the arguments and calls :lists.map:

: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:

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