vertexbuffer

vertexbuffer

Deleting item from a list

Hello, can anybody help here…? I have a list of players and I what to delete an element, but every for loop the list is reverting to original list. See code below

list = Enum.filter(players, fn(x) ->  # Sys.Log.debug("#{x["category"]}")
                x["category"] == category
            end)

              for _ <- 1..num do
                playerMapElement = Enum.random(list)

                List.delete(list, playerMapElement)

                player
            end

Most Liked

hazardfn

hazardfn

def remove_random_players_from_category(players, category, n) do
  players 
  |> Enum.filter(fn(player) ->
          player["category"] == category
      end) 
  |> remove_random_players(n)
end

def remove_random_players(players, 0), do: players
def remove_random_players(players, n) do
    random = players
    |> Enum.random
    players 
    |> List.delete(random)
    |> remove_random_players(n-1)
end

I haven’t actually tested this but suspect it’s what you are trying to do - it looks like you are trying to treat elixir like an imperative language (like Ruby).

I am also not sure this kind of “for loop” sugar on top of erlangs list comprehension is really the sort of thing you are looking for.

I have provided an example using recursion instead which is the usual way to do this kind of thing in erlang and elixir.

Feel free to ask questions about what I wrote and I will get back to you as quickly as I can. Or if I have mistaken what you are trying to do feel free to elaborate and I will get back to you :slight_smile:

Hope you are enjoying Elixir and stick with it - if it helps I came from a C# background before learning erlang and hit these kind of roadblocks all the time but it’s super rewarding!

brightball

brightball

The function returns the updated list. It doesn’t modify the list in place.

benwilson512

benwilson512

Author of Craft GraphQL APIs in Elixir with Absinthe

Couple of things here. The most important is that data is immutable.

Secondly however while this may seem like a nitpick, the formatting here makes it super hard to figure out what’s going on. A more idiomatic presentation of this code might be:

list = Enum.filter(players, fn(x) ->
  x["category"] == category
end)

for _ <- 1..num do
  player_map_element = Enum.random(list)

  List.delete(list, player_map_element)

  player
end

Note that I also made the player_map_element variable snake case instead of camel case.

It’s a bit hard to help you figure out what to do because there’s so much context missing. What is the player variable? Where does it come from? Why are you returning it from the loop that’s deleting stuff?

haroldvera

haroldvera

defp delete_list([], a, _), do: a

defp delete_list([h | t], a, f) do
case f.(h) do
true -> delete_list(t, a, f)
_ -> delete_list(t, a ++ [h], f)
end
end

def delete_from_list(a, f), do: delete_list(a, [], f)

testing,

f = fn (a) -> fn(x) -> a == x.name end end

delete_from_list [%{name: “a”}, %{name: “b”}, %{name: “c”}], f.(“b”)

Where Next?

Popular in Questions Top

belgoros
I’m not a pro in using Regex and can’t figure out why the following behaviour happens, especially if we take into account the difference ...
New
albydarned
Hello all! I am typing this post from my new MacBook Pro with the M1 chip. I’m loving it so far, and will probably use it as my daily dr...
New
romenigld
I am trying to run a deploy with docker and I successfully runned with this command: docker build -t romenigld/blog-prod . but when I t...
New
vertexbuffer
Hello, can anybody help here..? I have a list of players and I what to delete an element, but every for loop the list is reverting to ori...
New
myronmarston
The Elixir Typespec docs show the following syntax for keyword lists in typespecs: # ... | [key: type] # keyword lis...
New
gonzofish
I’m currently trying to understand how to join three tables using Ecto. All the examples I’ve seen use 2, so maybe I’m just missing somet...
New
stefanluptak
Hello everybody, usually, I use a 29" ultra-wide monitor for VSCode which can easily accomodate explorer (files panel) + file with code ...
New
wernerlaude
In AR this is so simple @articles = current_user.articles How to do in Ecto? def index(conn, _params) do current_user = conn.assig...
New
joeerl
Hello again - after a longish gap I’ve decided I really must dig into Elixir and see what’s been happening here - so I have a few questio...
New
idi527
I’ve been re-reading swift book again and noticed that multiline strings there don’t have a trailing line break, unlike in elixir iex(2)...
New

Other popular topics Top

Patoshizzle
After calling mix ecto.create I get this error: 17:00:32.162 [error] GenServer #PID&lt;0.412.0&gt; terminating ** (Postgrex.Error) FATAL...
New
vrod
I am using the Starship cross-shell prompt – it seems pretty nice, but I get some errors: [WARN] - (starship::utils): Executing command ...
New
senggen
Erlang/OTP 25 [erts-13.2.2] [source] [64-bit] [smp:8:8] [ds:8:8:10] [async-threads:1] 15:22:35.803 [error] gen_event {lager_file_backend...
New
lessless
I believe there are people here who are dealing with CSV files import on the daily basis, and since Excel is a really popular tool there ...
New
openscript
Hello! Sorry for this astonishing simple question, but I’m really stuck. I try to set up the intellij-elixir plugin, but I don’t know ho...
New
axelson
This post is a wiki (feel free to hit the edit button near the bottom right of this post to add your own changes!) This post collects co...
239 45766 226
New
mgjohns61585
Could someone help me? I'm making my first elixir program, number guessing game. I can't figure out how to convert the user's guess from ...
New
danschultzer
None of the current solutions worked well for me, so I went ahead and built a user management system from scratch. This project took far...
548 27727 240
New
ovidiubadita
Hey all, I discovered Elixir and I love it. I always wanted to learn a functional programming and I intended to go for Haskell, but afte...
New
WestKeys
Currently suffering from paralysis by [HTTP client] analysis. This is rather unusual in Elixirland as there tends to be consensus on the ...
New

We're in Beta

About us Mission Statement