Integers into a new list

So basically I’m trying to get all the integers in the matrix into another list and I’ve tried the following code:

matrix = [[1,2,3,"na",5], [2,3,"na",6]]
list = []
for r <- matrix do
for num <- r do
if is_integer(num)do

When i run the code it gives me no output.

There are two things here.

  1. Elixir is a language with immutable data. You cannot update a value, you can only create a new one. So it needs to be new_list = List.insert_at(list, -1, num)

  2. Lexical scoping allows you to reassign an existing variable a new value, but that variable will be scoped to the current scope and won’t probagate to outer scopes. A for do/end block is a scope boundary, so variables assigned within won’t be accessible from the outside (even if they shadow a variable set on the outside as well).

This means you’d need to restructure your approach, so it can actually return your aggregated result.

1 Like

The third thing:
3. for indicates a comprehension in Elixir, not a “for loop”. They’re much more powerful, and, in fact, your solution is not far from a one line for-comprehension solution

1 Like

You are close. This should help you: Comprehensions - The Elixir programming language