DOKL57

DOKL57

Hi all, the question seems like a simple question, but it has thrown me for a long time. I have a loop in which I loop through an element of the map list and I need to add the current item to the new list.
For a better understanding, here is a simpler example:

current_list = []
for x <- 1..10 do
current_list = [x | current_list]
end

I expect to get [1,2,3,4,5,6,7,8,9,10] in current_list, but got
What am I doing wrong? Thanks in advance!

Showing Posts 1 to 10

Aetherus

Aetherus

The current_list inside the for-loop is not the same variable as the current_list outside the for-loop. Actually, the current_list inside each loop is different.

I bet you’ve heard that in Elixir, everything is immutable, which means if a list is empty, it stays empty for the rest of its life. You can’t stuff things into it, or remove things from it, or change any of its elements.

So, the correct way is:

current_list = []
current_list =
  for x <- 1..10, reduce: current_list do
    acc -> [x | acc]
  end

or

current_list = []
current_list = Enum.reduce(1..10, current_list, fn x, acc ->
  [x | acc]
end)
kokolegorille

kokolegorille

or simply :slight_smile:

current_list = Enum.reduce(1..10, [], fn x, acc ->
  [x | acc]
end)
Aetherus

Aetherus

I guess the author may have put something in the current_list before starting the loop :slight_smile:

If the current_list is initially empty, then Enum.reverse(1..10) should be the shortest code.

derek-zhou

derek-zhou

IMHO, newbies should stay away from if, for or with until being comfortable with functional style programming. They are only syntactical sugar to make things shorter; they don’t provide any vital functionalities.

christhekeele

christhekeele

IDK, if is such a common core construct it feels like it would be off-putting to try to learn a lang where that was discouraged. In fact I’d say it’s the ideal candidate from which to learn this functional scoping lesson!

LostKobrakai

LostKobrakai

Lexical scoping isn’t limited to functional languages. Many languages use that type of scoping.

Usually people don’t expect do/end blocks to be scope boundries though.

christhekeele

christhekeele

Right! The combination of lexical scoping, expression return values, resulting in do/end variables being local and needing to assign out of them, is what’s the useful take-away.

I think if is great lesson in this, because

  • newcomers will often reach for it early
  • trying to re-assign something out of scope (which is commonly possible in other lexically scoped languages; that’s kind of what I meant by “functional” lexical scoping)
  • possibly discover after the assigning-result refactor that if they want the fallback case to be non-null, they also can return out of else
  • which sets them up for success when the conditional branching becomes more comples and they needbti reach for case; they will have acquired the understanding they need to succeed
derek-zhou

derek-zhou

A cond do ... will raise if none of the conditions hold true. This is safer for newbies than if that don’t have a else clause.

NobbZ

NobbZ

Yes, though paired with immutability and implicit shadowing it is sometimes a bit weird.

foo = 0
if true, do: foo = 1
IO.puts(foo)

If you do not know about the implicit shadowing, which is dropped again after leaving the ifs lexical scope, then it is not obvious what happens.

The problem is not the scoping, its the shadowing, which is often seen as a bad design decision.

christhekeele

christhekeele

I suppose the compiler could warn on reassignment of shadowed variables. There are legitimate use-cases for it though, especially in more involved conditional bodies. Especially in reduces!

Where Next? Top

Trending in Questions Top

katta
I having some trouble figuring out if I have set myself too strict of standards for my production server. Currently I can handle 75% of r...
New
achenet
Hello, I’m trying to build a basic Phoenix web-app, and I’d like to use Tailwind. However, when I launch mix phx.server, I get an error...
New
kpanic
Hi everyone, I am toying with the idea of building a “match maker” for giving personal help to people that wants to start coding. I sta...
New
Cxx-mlr
I’m working on a small exercise involving update_in/3, and I came up with this solution: data = %{ name: "Periodic Table", category:...
New
ChrisAmelia
I’ve got trouble wrapping my head around the order in which functions are called in this snippet (from Phoenix’s authentication): toke...
New
dillonoconnor
Is there any way to avoid the Hologram compiler running when using iex? It seems like the front-end code could potentially be disregarded...
New
thiagogsr
** (ArgumentError) expected :max_attempts to be a positive integer, got: {:@, [line: 10, column: 19], [{:max_attempts, [line: 10, column:...
New

Other Trending Topics Top

GenericJam
Edit: 2026 May 15 - This post is archived. Mob is alive!! Main docs: mob v0.7.11 — Documentation A bit of explanation for the slightly c...
New
mudasobwa
I am happy to introduce the very α version of the new programming language compiled to BEAM. Welcome Cure. It has literally three kille...
New
garrison
Hobbes is a low-level distributed database for the Elixir programming language. Hobbes provides a simple, safe, and scalable storage lay...
New
budgie
A little off-topic, but I feel like people here have a good head on their shoulders. I used to be quite good at making software. Was luc...
New
KristerV
Hey. Is there anyone here who creates agents in their apps? Not talking about using agents, but creating them. I’m finding it pretty diff...
New
mcass19
ExRatatui lets you cook up rich terminal UIs in Elixir, powered by Rust’s ratatui via Rustler NIFs. Build interactive terminal applicatio...
New

We're in Beta

About us Mission Statement

Options

Thread Display Mode




Thread Preview

Skip Thread Previews