Small Erlang bencode library

Steve Smith ssmith@REDACTED
Thu May 18 02:19:19 CEST 2006


[There may be a blank reply with this one: I've officially had-it with
Evolution now ...]

On Wed, 2006-05-17 at 09:58 +0200, Christian S wrote:
> This is how i would build the encoder. 

Hi Christian, thanks for the comments:

> bencode(List) when is_list(List) ->
>         [$l, [bencode(Item) || Item <- List], $e]; 
> bencode(Int) when is_integer(Int) ->
>         [$i, integer_to_list(Int), $e];
> bencode(Bin) when is_binary(Bin) ->
>         [integer_to_list(size(Bin)), $:, Bin];
> 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.  I didn't know about the "element(1, Dict) ==
dict" trick either, that's useful.  I'm not sure about the
string==binary thing though, that feels like another form of 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).

Of course, having written my first Erlang program I now feel qualified
to pick holes :)

Cheers,
Steve







More information about the erlang-questions mailing list