bartblast

bartblast

Creator of Hologram

After having some experience with Elixir I decided to read “Programming Elixir 1.6” by Dave Thomas for the second time, this time very thoroughly. I noticed something strange for me on page 37 (chapter Variable Scope):

Elixir doesn’t really have blocks such as these, but it does have ways of grouping expressions together. The most common of these is the do block:

line_no = 50
if (line_no == 50) do
IO.puts “new-page\f”
line_no = 0
end

IO.puts line_no

However, Elixir thinks this is a risky way to write code. In particular, it’s easy to forget to initialize line_no outside the block, but to then rely on it having a value after the block. For that reason, you’ll see a warning:

$ elixir back_block.ex
warning: the variable “line_no” is unsafe as it has been set inside one of: case, cond, receive, if, and, or, &&, ||. Please explicitly return the variable value instead. Here’s an example:

case integer do
  1 → atom = :one
  2 → atom = :two
end

should be written as

atom =
case integer do
  1 → :one
  2 → :two
end

Unsafe variable found at:
T.ex:10

0

TL;DR: A variable is initialized in the outer scope of if, then inside the if block it’s rebinded to a new value and the binding propagates to the outer scope.

I was always under the impression that in such case a new inner scope is created and you can’t change the binding in the outer scoped, so the result would be 50, and not 0, as in the quoted book snippet.
Did something change in the language since 1.6 or am I missing something?

Showing Posts 1 to 2

NobbZ

NobbZ

Yes, imperative assignment has been removed from the language in 1.8 or 1.7.

bartblast

bartblast OP

Creator of Hologram

Good to know! Thank you @NobbZ !

— All posts loaded —

Where Next? Top

Trending in Chat/Questions Top

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
JesseHerrick
Hey, I’m Jesse and I’m the main contributor behind Dexter, a full-featured, lightning-fast Elixir LSP optimized for large codebases. It s...
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
marciok
Hi there! We created Gust: A task orchestrator inspired by Airflow. For those who have never heard about Aiflow, it’s a Python-based wor...
New
mhanberg
Hi everyone! The first release candidate for the Expert language server project is now available! We’ve published a press release detai...
New
jimsynz
Beam Bots (or just BB for short) is a framework for building fault-tolerant robotics applications in Elixir using familiar OTP patterns. ...
New

We're in Beta

About us Mission Statement

Options

Thread Display Mode




Thread Preview

Skip Thread Previews