user1501127
user1501127

Reputation: 865

Records pattern matching in Erlang

For fun i am trying to recreate one of my favorite boardgames in Erlang and I am trying pattern match a nested record and I always get the error msg no matter what I try:

** exception error: no function clause matching 
                kingoftokyo_server:add_player("john",
                  {gamestate,[],[],[],[]}) (kingoftokyo_server.erl, line 40)

my code looks like this:

 -record(player,{playerName,cards,energy}).
 -record(board,{city_center,outside}).
 -record(gamestate,{board,player,dices,game_round}).

 add_player(Name,{Board,{PlayerName,Cards,Energy},Dices,Game_round}) ->
    NewList = lists:append(Name, PlayerName),
    NewState = {Board,{NewList,Cards,Energy},Dices,Game_round},
    NewState.

I dont see why the clause does not match in the add_player function. I have tried all I could find but don't get why this does not work.

Any pointers would be greatly appreciated!

Upvotes: 4

Views: 2830

Answers (1)

Dogbert
Dogbert

Reputation: 222128

Erlang records are tuples but they have an extra field as the first element: the name of the record. That is, with the records you've defined, #board{city_center = 1, outside = 2} equals {board, 1, 2}. While you can use a tuple pattern to extract the fields, that will break if you ever decide to reorder any field. You can use the record pattern matching syntax to match the fields by their name.

The following code should work for you:

add_player(Name,
           #gamestate{
             board = Board,
             player = #player{playerName = PlayerName, cards = Cards, energy = Energy},
             dices = Dices,
             game_round = Game_round}) ->

Upvotes: 4

Related Questions