Polymorphic record question

Bengt Kleberg bengt.kleberg@REDACTED
Mon Jun 19 11:06:10 CEST 2006


On 2006-06-19 10:16, Andrew Lentvorski wrote:
> I define some basic packet records.  Every packet has a sequence number, 
> and I would like to be able to pull out that sequence number regardless 
> of packet type like so:
> 
> -module(test).
> 
> -compile(export_all).
> 
> -record(u_P2PGen, {sequenceNumber}).
> -record(u_P2PSyn, {sequenceNumber, synData}).
> -record(u_P2PFin, {sequenceNumber, finData}).

...deleted
> Obviously, with different types of packets hitting the queue, I don't 
> know a priori which packet type it is.  Thus why I use a generic packet 
> to get at the sequence number.
> 
> My question is: Is this "downcast" the only/best way of doing this kind 
> generic handling?

it is not the only way. this is another way of doing it:

-record(u_P2P_seq, {number, packet}).
-record(u_P2P_syn, {data}).
-record(u_P2P_fin, {data}).

test() ->
     Q0 = queue:new(),
     Q1 = queue:in(#u_P2P_seq{number=1, packet=#u_P2P_syn{data=foo}}, Q0),
     Q2 = queue:in(#u_P2P_seq{number=9, packet=#u_P2P_fin{data=bar}}, Q1),
     io:format("Q2: ~p~n", [Q2]),

     {{value, P0}, Q3} = queue:out(Q2),
     io:format("P0: ~p~n", [P0]),
     io:format("SN: ~p~n", [P0#u_P2P_seq.number]).


bengt
-- 
    EPO guidelines 1978: "If the contribution to the known art resides
    solely in a computer program then the subject matter is not
    patentable in whatever manner it may be presented in the claims."



More information about the erlang-questions mailing list