I was reading Elixir in Action by Saša Jurić and came across an example that, with a little modification, demonstrated some useful similarities between Elixir and Python, which might be helpful for another Elixir noobs like me who know a little Python. This straightforward example takes a list of names and prints them with an index.
It begins with a list construction that looks exactly like what you'd see in Python. The following line is an Elixir list comprehension. It begins with for
but otherwise is similar to list comprehensions in Python. You'd read it in English as: "For each {name, index} pair in Enum.with_index(employees), print the formatted result."
IO.puts()
is similar to print()
, and the "#{variable}"
syntax is quite similar to Python's f-strings.
This list comprehension is iterating over Enum.with_index(employees)
, which is analogous to Python's enumerate()
in that it returns a tuple of {value, index}
for each element of the iterable, although in Elixir the value comes first, then the index.
In Python, the final list comprehension might look like this:
[print(f"{idx}. {value}") for idx,value in enumerate(employees)]
I'll leave it to you to decide if either is more clear than the other. My experience so far is that Elixir comprehensions are more flexible and powerful.
For example, if your comprehension generates tuples, you can use the syntax into: %{}
to build a map (a dictionary in Python) where the first element of the tuple is the key and the second element is the value.
As with dictionaries in Python, you can get the value of a map entry by key using the map_name[key]
syntax.
Granted, you could do the same thing in Python using a dictionary comprehension:
employee_dict = {key:value for (key, value) in enumerate(employees)}
It's really been fun learning Elixir. I may pass along more tips and tidbits down the road.
Top comments (0)