Erlang: The Amazingly Funky and the Amazingly Cool

Anyone who's ever looked at Erlang knows that the syntax is downright strange. For instance, Python uses "#" for comments, but Erlang interprets "8#7" as 7 in base 8 notation. Python uses "%" for modulo, but Erlang uses "%" for comments. Erlang uses "rem" for modulo, but "rem" is used as a comment delimiter in some other syntaxes.

However, I ran across some other cool tidbits. If M is a 16 bit binary value, you can unpack the first 3 bits into X, the next 7 bits into Y, and the last 6 bits into Z using the syntax:
<<X:3, Y:7, Z:6>> = M
Hence, you can parse an IPv4 datagram in a single pattern-matching operation (taken from "Programming Erlang: Software for a Concurrent World" p. 99):
-define(IP_VERSION, 4).
-define(IP_MIN_HDR_LEN, 5).
DgramSize = size(Dgram),
case Dgram of
<<?IP_VERSION:4, HLen:4, SrvcType:8, TotLen:16,
ID:16, Flgs:3, FragOff:13,
TTL:8, Proto:8, HdrChkSum:16,
DestIP:32, RestDgram/binary>> when HLen >= 5, 4*HLen =< DgramSize ->
OptsLen = 4*(HLen - ?IP_MIN_HDR_LEN),
<<Opts:OptsLen/binary,Data/binary>> = RestDgram,
That's about as cool as it gets for implementing binary protocols!


Unknown said…
About '%' for comments: AFAIK, Erlang was born as Prolog-metainterpreter, and in Prolog comments start with '%'.
Binary syntax is cool, agreed.
Unknown said…
% is also the comment character in TeX, and #: is "binary representation" in J. And "rem" is defined in the Haskell Standard Prelude. So it's what you're used to, I guess :-)
Anonymous said…
Why didn't they call it mod(ulus) instead of rem(inder)...
Anonymous said…
I used remainder at primary school. It wasn't until I started programming I found out the technical term (modulus).
Chris Smith said…
Well, modulus and remainder are different things, when negative numbers are involved. For what it's worth, Haskell defines both. In fact, it has div (divide), quot (quotient), mod (modulus), and rem (remainder). div/mod are a pair, and quot/rem are another pair.
jjinux said…
That's *so* Haskell ;)
Anonymous said…
Funny, I know "rem" from MS DOS batch scripting days :-) I always thought it was short for "remove", ha ha ha!