Getting error: no match of right hand side value

Background: Writing a card game simulator. Assume an initial state with 5 cards. The play_card function plays(discard) the first card from the list (state). A message is written to the shell and the state updated. A second call would then do the same and update the new state. I am getting an error on the line “{:reply, “#{cardplayedname}”, new_state}”, the return from the handle_call callback. What am I doing wrong? Any help is appreciated.

The error message is "no match of right hand side value: “ping1"”. That’s indicating a pattern matching error. Bit, I am unable to see why.

defmodule DBGame.Ping do
    use GenServer

#client api
def start_link(opts \\ []) do
    state = ["ping1","ping2","ping3","ping4","ping5"]
    GenServer.start_link(__MODULE__, state, opts)
end

def play_card(pid, cardplayedindex) do
    GenServer.call(pid, {:card, cardplayedindex})
end


#server callbacks    
def init(:ok, state) do
    {:ok, state}
end

def handle_call({:card, cardplayedindex}, _from, state) do
    case(card_played(cardplayedindex, state)) do
        {:ok, cardplayedname} -> 
            new_state = update_stats(state, cardplayedname)
            {:reply, "#{cardplayedname}", new_state}
        _ ->
            {:reply, :error, state}
    end
end


#helper functions
defp card_played(cardplayedindex, state) do
    cardplayedname = Enum.at(state, cardplayedindex, "nocard")
    IO.puts("#{cardplayedname} is played")
    {:ok, cardplayedname}
end

defp update_stats(state, cardplayedname) do
    new_state = List.delete(state, cardplayedname)
    #new_stat = state
end

end

Strange, I can run it without a problem:

✓ src ➤ iex test.exs
Erlang/OTP 18 [erts-7.3] [source] [64-bit] [smp:8:8] [async-threads:10] [hipe] [kernel-poll:false] [dtrace]

test.exs:39: warning: variable new_state is unused
Interactive Elixir (1.2.3) - press Ctrl+C to exit (type h() ENTER for help)
iex(1)> {:ok, p} = DBGame.Ping.start_link()
{:ok, #PID<0.63.0>}
iex(2)> DBGame.Ping.play_card(p, 0}
** (SyntaxError) iex:2: unexpected token: "}". "(" starting at line 2 is missing terminator ")"

iex(2)> DBGame.Ping.play_card(p, 0)
ping1 is played
"ping1"
iex(3)> DBGame.Ping.play_card(p, 0)
ping2 is played
"ping2"
iex(4)> DBGame.Ping.play_card(p, 0)
ping3 is played
"ping3"
iex(5)> DBGame.Ping.play_card(p, 0)
ping4 is played
"ping4"
iex(6)> DBGame.Ping.play_card(p, 0)
ping5 is played
"ping5"
iex(7)> DBGame.Ping.play_card(p, 0)
nocard is played
"nocard"
iex(8)> DBGame.Ping.play_card(p, 2)
nocard is played
"nocard"

What did you run to get the error?

2 Likes

Well, right after seeing your reply, I closed everything and ran it. It works now. Weird. I also made sure I’m running

iex -S mix

every time I made a change. I don’t know why it acted the way it did. I spent almost two hours just on this. Thank you for running it and making me try again.