Get value from a list inside a map elixir

Viewed 144

I have a struct that looks like this:

defmodule WarGame.Core.Game do
 
  defstruct user_cards: [],
        croupier_cards: [],
        user_bets: [],
        bets: [:card_odd, :color_player],
        deck: %{},
        used: [],
        title: nil

I would like to create a function that can take a chosen element of a list bets and move it to user_bets. How could I achieve this? There will be only finite (5) elements in this list.

In my head it looks something like this:

def select_bet(bet) do
  finds bet in %WarGame.Core.Game{}.bets
  inserts it to %WarGame.Core.Game{}.user_bets
end

How can I achieve this?

1 Answers

is immutable, hence your function should receive both a struct and bet in the first place. It would return a modified struct if the bet has been found, and an unmodified struct otherwise.

The simplest way would be to check if -- [bet] modifies the bets, and if so, add the bet to the user_bets.

def select_bet(%WarGame.Core.Game{} = game, bet) do
  game_bets = game.bets # for the pin operator to work

  {bets, user_bets} =
    case game_bets -- [bet] do
      ^game_bets -> {game_bets, game.user_bets}
      bets -> {bets, [bet | game.user_bets]}
    end

  %WarGame.Core.Game{game | bets: bets, user_bets: user_bets}
end

Or, even more concise.

def select_bet(%WarGame.Core.Game{} = game, bet) do
  game_bets = game.bets # for the pin operator to work

  case game_bets -- [bet] do
    ^game_bets -> 
      game
    bets ->
      %WarGame.Core.Game{game |
        bets: bets, 
        user_bets: [bet | game.user_bets]}
  end
end
Related