| Author |
Message |
< Erlang ~ Using keyfind |
| klm |
Posted: Sat May 23, 2009 9:11 pm |
|
|
|
User
Joined: 11 May 2009
Posts: 18
|
Hello !
I'm trying to use the function keyfind but I don't understand how does it works.
Indeed I've done a record
(new_player is a personnal function to create a new player)
Player1= new_player(1,{192,168,1,10},"nameone"},
Player2 = new_player(2,{192,168,1,10},"nametwo"},
List = [Player1,Player2],
My_tuple = lists:keyfind("nameone", 3, List),
io:format("Find the tuple ~w ~n",[My_tuple#player.num]).
and I've got this error :
** exception error: {badrecord,player}
in function test:new/0
Could you explain me how to use the function keyfind ?
thanks !
and if you know too how to do real random (seed() blocks the program) I'm interested  |
|
|
| Back to top |
|
| ates |
Posted: Mon May 25, 2009 10:13 am |
|
|
|
Joined: 23 May 2009
Posts: 3
|
I hope it help:
1> Player1 = {1, {1,2,3,4}, "player1"}.
{1,{1,2,3,4},"player1"}
2> Player2 = {2, {4,3,2,1}, "player2"}.
{2,{4,3,2,1},"player2"}
3> List = [Player1, Player2].
4> lists:keyfind("player2", 3, List).
{2,{4,3,2,1},"player2"}
5> rd(player, {id, ip, name}).
player
6> Tuple = lists:keyfind("player2", 3, List).
{2,{4,3,2,1},"player2"}
7> {ID, IP, Name} = Tuple.
{2,{4,3,2,1},"player2"}
8> Tuple2 = #player{id = ID, ip = IP, name = Name}.
#player{id = 2,ip = {4,3,2,1},name = "player2"}
9> io:format("Results: ~p~n", [Tuple2#player.id]).
Results: 2
ok |
|
|
| Back to top |
|
| uwiger |
Posted: Mon May 25, 2009 10:24 am |
|
|
|
User
Joined: 03 Jul 2006
Posts: 604
Location: Sweden
|
klm wrote: Indeed I've done a record
(new_player is a personnal function to create a new player)
Player1= new_player(1,{192,168,1,10},"nameone"},
Player2 = new_player(2,{192,168,1,10},"nametwo"},
List = [Player1,Player2],
My_tuple = lists:keyfind("nameone", 3, List),
You should really try the commands one by one in the shell, but the problem here is that a player record would have to have the atom 'player' as a first element. So printing out the records in question:
Player1 = {player,1,{192,168,1,10},"nameone"},
Player2 = {player,2,{192,168,1,10},"nametwo"},
Then using keyfind(), you'd have to search on the fourth element (including the tag), not the third.
Using record syntax, you can also write
lists:keyfind("nameone",#player.name,List). |
|
|
| Back to top |
|
| klm |
Posted: Mon May 25, 2009 10:48 am |
|
|
|
User
Joined: 11 May 2009
Posts: 18
|
Yes thanks
I tried and it works, I did'nt found how it works in the man on erlang.org
It was easiest to use than I thought
Erlang is powerful but it's difficult after programming in C language or Java |
|
|
| Back to top |
|
|
|
All times are GMT
|
|
You cannot post new topics in this forum You cannot reply to topics in this forum You cannot edit your posts in this forum You cannot delete your posts in this forum You cannot vote in polls in this forum You cannot attach files in this forum You cannot download files in this forum
|
|
|