[erlang-questions] Maps & records: binding directly to bitstring comprehensions

Felix Gallo <>
Thu Feb 6 23:35:18 CET 2014

I live in a world of pain wherein I receive 4K binary blob packets with a
tightly packed schema that changes every few weeks.

One way to handle it is, e.g., (field names changed to anonymize the

-define(PACKET, <<Version:8, Flavor:3, Moisture:5, IsDelicious:1, [...],
IsFattening:1 >>).

(and then, in my state machine...)

s_connected(P = ?PACKET) ->
  io:format("Moisture: ~p~n", [Moisture]), %% twitch

and conversely

mold_together_a_packet(Version, Flavor, Moisture, IsDelicious, ...) ->

or if I wanted to put some modicum of discipline on that thing maybe
something like:

-define(OUTGOINGPACKET, [Version, Flavor, Moisture, IsDelicious, ...]).

mod_together_a_packet(?OUTGOINGPACKET) ->

both of these things seem iffy and super messed up because I have to define
each field separately each in two different macros, and also the namespace
pollution is bad.  Maybe I'm doing it wrong, but those seem to me like the
best of a set of bad ways to do it.  Yet, it seems like the language knows
enough to be *able* to bind a bitstring comprehension directly to a record,
and probably will know enough soon to bind it directly to a map.


<<M#Version:8, M#{ Flavor }:3, M#{ Moisture }:5, M#{ IsDelicious }:1, M#{
Color }#{ Red }:8, M#{ Color }#{ Blue } :8, M#{ Color }#{ Green }:8, M#{
IsFattening } :1 >> = P

and also

<<M#Version:8, M#{ Flavor }:3, M#{ Moisture }:5, BitDepth:8, M#{ Color }#{
Red }:BitDepth, M#{ Color }#{ Blue } :BitDepth, M#{ Color }#{ Green
}:BitDepth, M#{ IsFattening } :1 >> = P

and also the science fictional:

SchemaType = #{ Version: 8, Flavor: 3, Moisture: 5, ... }, %% assumes
insert ordering on maps instead of term ordering because I prefer it that
<<M = SchemaType>> = P,
M#{ Flavor } = 5,
<<SchemaType = M>>.

disclaimer: not a programming language theorist.

anyway, it would be super great if something like this were to exist; or,
if there's something better than the nasty macro magic I ended up using
that is a second place finisher in the absence of this, I'd love to know
what it is.

-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://erlang.org/pipermail/erlang-questions/attachments/20140206/cd4c5a67/attachment.html>

More information about the erlang-questions mailing list