Please Help anyone! I am trying to print the list using for loop but i am getting this error, I am very new to elixir and din't konw how to solve this
defmodule Todos do
def matrix_of_sum do
[
[21 ,"na", "na", "na", 12],
["na", "na", 12, "na", "na"],
["na", "na", "na", "na", "na"],
[17, "na", "na", "na", "na"],
["na", 22, "na", "na", "na"]
]
end
# print the rows and colums off the tuple in elixir
def print_list do
for i <- 0..4 do
for j <- 0..4 do
if matrix_of_sum[i][j] != "na" do
IO.puts matrix_of_sum[i][j]
end
end
end
end
end
#Error
** (ArgumentError) the Access calls for keywords expect the key to be an atom, got: 0
(elixir 1.14.0) lib/access.ex:313: Access.get/3
(todos 0.1.0) lib/todos.ex:15: anonymous fn/3 in Todos.print_list/0
(elixir 1.14.0) lib/enum.ex:4299: Enum.reduce_range/5
(todos 0.1.0) lib/todos.ex:14: anonymous fn/2 in Todos.print_list/0
(elixir 1.14.0) lib/enum.ex:4299: Enum.reduce_range/5
(todos 0.1.0) lib/todos.ex:13: Todos.print_list/0
iex:24: (file)
In Elixir, lists cannot be accessed by list[index]
using the Access
behaviour.
You could use Enum.at/2
, like:
matrix_of_sum |> Enum.at(i) |> Enum.at(j)
But this would be inefficient: Elixir lists are linked lists and accessing by index has a linear cost.
What you want instead is to directly use for
directly on the lists:
for row <- matrix_of_sum, cell <- row do
if cell != "na" do
IO.puts(cell)
end
end
The reason why the error is a bit confusing is because Access
tries to read the list as a keyword list: it would then need i
to be an atom key, not an integer.