Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to convert list of strings to list of integers?

Tags:

elixir

I am trying to request a list of numbers (ex: "1 2 3 4 5 6") and output a list of integers (ex: "[1, 2, 3, 4, 5, 7]"). I have come up with the following code:

IO.gets ("Enter a list: ")
|> String.trim
|> String.split
|> Enum.map(&String.to_integer/1)

This will not compile and gives me the following error:

== Compilation error in file test.ex ==
** (ArgumentError) argument error
    :erlang.binary_to_integer("Enter")
    (elixir) lib/enum.ex:1270: Enum."-map/2-lists^map/1-0-"/2
    test.ex:4: (file)
    (elixir) lib/kernel/parallel_compiler.ex:121: anonymous fn/4 in 
Kernel.ParallelCompiler.spawn_compilers/1

I have run this code one line at a time through iex using the result of each function as an input to the next and achieve the correctly formatted list BUT when I put it all together in a file and run it, it won't even compile...

Any assistance would be great.

like image 682
RdnCdn Avatar asked Aug 31 '25 04:08

RdnCdn


1 Answers

The problem is a space between IO.gets and the opening parenthesis. This would work:

IO.gets("Enter a list: ")
|> String.trim
|> String.split
|> Enum.map(&String.to_integer/1)

Operator precedence matters:

#  3           1
IO.inspect (IO.inspect(42, label: "foo"))
#     2 
|> IO.inspect(label: "bar")

foo: 42
bar: 42
42

Let’s see what happened here: I placed numbers denoting the order of execution. The first executed is "foo", then "bar", and only then the firstly placed inspect. That happens because Elixir allows (although discourages) function calls without parentheses, and pipe |> takes a precedence over the function call.

like image 104
Aleksei Matiushkin Avatar answered Sep 04 '25 22:09

Aleksei Matiushkin