0

I'm currently learning Elixir and going through all exercises in the "Programming Elixir 1.6" book. As exercises itself are pretty simple, I struggle to understand something concerning outputs.

At the end of chapter 5, I'm asked to rewrite those lines using anonymous functions :

Enum.map [1, 2, 3, 4], fn x -> x + 2 end
Enum.each([1, 2, 3, 4], fn x -> IO.inspect x end

So I wrote this :

Enum.map([1, 2, 3, 4], &(&1 + 2))
Enum.each([1, 2, 3, 4], &IO.inspect/1)

But after running this my output was only from the inspect :

λ elixir functions-5.exs
1
2
3
4

So I added some IO.puts in here :

IO.puts Enum.map([1, 2, 3, 4], &(&1 + 2))
IO.puts Enum.each([1, 2, 3, 4], &IO.inspect/1)

And the output was really strange, to say the least :

λ elixir functions-5.exs
╚╝║═
1
2
3
4
ok

After trying some alternative syntax and using variables in between calls, I tried to execute those lines directly into Interactive Elixir :

iex(2)> Enum.map([1, 2, 3, 4], &(&1 + 2))
[3, 4, 5, 6]

It works fine this way! Why?

iex(1)> IO.puts Enum.map([1, 2, 3, 4], &(&1 + 2))
╚╝║═
:ok

IO.puts seems to break formatting again, why again?

What am I missing? why the different context of executions doesn't have the same output?

To summarize my overall question: Whiskey Tango Foxtrot ???

Mahaal
  • 1
  • 1

1 Answers1

1

The value you're passing to IO.puts is a list of integers, and IO.puts interprets lists of integers as lists of Unicode codepoints (of which ASCII codes are a subset):

iex(1)> IO.puts [70,111,111]
Foo
:ok
iex(2)> IO.puts [1087, 1088, 1080, 1084, 1077, 1088]
пример
:ok

I'm not sure why you got ╚╝║═; I get different output for that list:

iex(1)> IO.puts [3,4,5,6]
^C^D^E^F
:ok

IO.inspect, on the other hand, tries to print the source code representation of whatever you pass to it.

legoscia
  • 39,593
  • 22
  • 116
  • 167
  • Oh thanks that explains a lot, can you tell me why the Enum.map doesn't have any output in the .exs file but has one in the Interactive Elixir? – Mahaal Jan 22 '20 at 12:25
  • When you run a `.exs` file with the `elixir` command, it doesn't print anything automatically, only what you explicitly tell it to print using `IO` functions. On the other hand, Interactive Elixir always prints the _result_ of every expression you type into it. – legoscia Jan 22 '20 at 12:46
  • Thanks for all those explanations! – Mahaal Jan 22 '20 at 14:41