5 ms·
Have you seen Elixir list comprehensions? iex> for n <- 1..4, do: n*n [1, 4, 9, 16] Or for your example: iex> l = 1..3 # equivalent to [1,2,3] iex> E
by pythonaut_16 3y ago
Have you seen Elixir list comprehensions?
iex> for n <- 1..4, do: n*n
[1, 4, 9, 16]
Or for your example:
iex> l = 1..3 # equivalent to [1,2,3]
iex> Enum.reduce(l, fn item, acc -> acc + item end)
# or
iex> Enum.reduce(l, &(&1+&2)
# or the built in
iex> Enum.sum(l)
# all return:
6
https://elixir-lang.org/getting-started/comprehensions.html https://elixir-lang.org/getting-started/comprehensions.html
https://hexdocs.pm/elixir/1.12/Enum.html#reduce/2 https://hexdocs.pm/elixir/1.12/Enum.html#reduce/2
https://hexdocs.pm/elixir/1.12/Enum.html#sum/1 https://hexdocs.pm/elixir/1.12/Enum.html#sum/1
None of which take away from your point though: it's definitely a different mental model than you use for Python/Go/Javascript.
- deleted 3y ago[deleted]
- chubot 3y agoYes though Python has list comprehensions too :) I should have picked a different example -- the idea I was trying to get across was that mutability within a loop is useful. Here’s a similar question I asked with Python vs. OCaml and Lisp. Short-circuiting loops seems to cause the code to become fairly ugly in functional languages https://old.reddit.com/r/ProgrammingLanguages/comments/puao1v/im_using_python_now_2013/he2syf8/ https://old.reddit.com/r/ProgrammingLanguages/comments/puao1...