Local accumulators for cleaner comprehensions

I haven’t been able to read all of the thread/s so apologise in advance if this is no longer possible or has since been agreed not to pursue (feel free to ignore this comment in that case) but just want to comment on this from the original thread:

I personally liked José’s original proposal without the explicit syntax as it’s the least jarring and looks the cleanest and easiest to read to me:

mut section_counter = 0
mut lesson_counter = 0

for section <- sections do
  if section["reset_lesson_position"] do
    lesson_counter = 0
  end

  section_counter = section_counter + 1

  lessons =
    for lesson <- section["lessons"] do
      lesson_counter = lesson_counter + 1
      Map.put(lesson, "position", lesson_counter)
    end

  section
  |> Map.put("lessons", lessons)
  |> Map.put("position", section_counter)
end

It also let’s people use their own signifier:

mut m_section_counter = 0
mut m_lesson_counter = 0

for section <- sections do
  if section["reset_lesson_position"] do
    m_lesson_counter = 0
  end

  m_section_counter = m_section_counter + 1

  lessons =
    for lesson <- section["lessons"] do
      m_lesson_counter = m_lesson_counter + 1
      Map.put(lesson, "position", m_lesson_counter)
    end

  section
  |> Map.put("lessons", lessons)
  |> Map.put("position", m_section_counter)
end

or:

mut acc_section_counter = 0
mut acc_lesson_counter = 0

for section <- sections do
  if section["reset_lesson_position"] do
    acc_lesson_counter = 0
  end

  acc_section_counter = acc_section_counter + 1

  lessons =
    for lesson <- section["lessons"] do
      acc_lesson_counter = acc_lesson_counter + 1
      Map.put(lesson, "position", acc_lesson_counter)
    end

  section
  |> Map.put("lessons", lessons)
  |> Map.put("position", acc_section_counter)
end

Personally I would use the original. Declaring them, and seeing how they’re used in code is enough for me to differentiate them.

1 Like