Small Erlang bencode library

Ulf Wiger (AL/EAB) ulf.wiger@REDACTED
Thu May 18 11:11:27 CEST 2006


Steve Smith wrote:
> 
> [...]
> > bencode(Dict) when element(1, Dict) == dict -> 
> >         Sorter = fun({Key1, _}, {Key2, _}) -> Key1 < Key2 end,
> >         Pairs = [[bencode(Key), bencode(Value)] || {Key, Value} <- 
> > lists:sort(Sorter, dict:to_list(Dict))],
> >         [$d, Pairs, $e].
> 
> My original version of the code used is_integer(), etc, but I 
> had to move to tuples when I realised there's no reliable way 
> to detect if a list is a string or not.

Yes, this is a bit tricky.

Joe Armstrong has played with the following convention in the past (e.g.
in his UBF implementation):

s(Str) -> {'#S', Str}.
-define(S(Str), {'#S',Str}).


start(Nick) ->
    ...
    {reply,{ok,_}, _} = rpc(Pid, {startService, s("irc_server"), []}),
    ...
    case rpc(Pid, {nick, s(Nick)}) of
        {reply, false, _} ->
            ...
        {reply, true, active} ->
            ...
    end,
    ...

handlerRpc(active, {nick, ?S(New)}, Nick, Manager) ->
    case ask_manager(Manager, {change_nick,Nick,New,self()}) of
        ok ->
            {true, active, New};
        error ->
            {false, active, Nick}
    end;

Basically, s(string()) constructs a string object, and ?S(Str)
matches on the string value.


>  I didn't know about the "element(1, Dict) == dict"
> trick either, that's useful.  

... but a violation of the common convention that you don't peek into
undocumented data structures, just because you can. :)

I was going to suggest that you use orddict instead of dict, partly to
eliminate the need for sorting.
Also, I'd stick with the tagging.


> Has anyone ever looked at adding stronger typing to Erlang 
> (*strong*, not static :), eg. the ability to define new types 
> that are checkable at runtime?  At the moment it looks like 
> people are adding their own ad-hoc typing via tagged-tuples 
> (although matching makes this much less messy that it could be).

There have been several attempts at adding typing to Erlang. The success
of Dialyzer has changed the landscape quite a bit, since dealing with
types in Erlang is suddenly almost comme il faut.

BR,
Ulf W



More information about the erlang-questions mailing list