[erlang-questions] program: custom output filters in the shell

Ulf Wiger <>
Sat Nov 10 12:19:48 CET 2007


Richard's presentation of the array module at the EUC inspired me
to try to address one of the notable drawbacks of using modules
like dict, gb_trees, xmerl, et al: when you get output in the shell,
they are not pretty to look at.

But the shell can be told to recognize records, and pretty-print
them. Why can't I tell it how to recognize other data structures
as well?

I include a hack of io_lib_pretty.erl and shell.erl that makes it so.
It is, as far as I can tell, backwards compatible, but allows you to
provide a fun along these lines:

fun(Term) -> {custom,Tag,Recurse,Output} | no

where Tag = atom()
           Recurse = boolean()
           Output = any()

Recurse tells the pretty-printer whether to apply the filter fun
recursively to Output as well.

(I think it could rather easily be extended to also support e.g.
{pre_formatted, Tag, IoList}, but I didn't do that.)

New shell commands:
fa(Tag, Fun)    - registers a filter fun
fl()                   - lists filter funs
fr(Tag)             - removes a filter fun

Example:

1> dict:from_list([{N,a} || N <- lists:seq(1,5)]).
{dict,5,
      16,
      16,
      8,
      80,
      48,
      {[],[],[],[],[],[],[],[],[],[],[],[],[],[],[],[]},
      {{[],
        [[3|a]],
        [],
        [],
        [],
        [],
        [[2|a]],
        [[5|a]],
        [],
        [],
        [],
        [[1|a]],
        [[4|a]],
        [],
        [],
        []}}}
2> rr(code:which(dict)).
[dict]
3> fa(dict,fun(#dict{}=D) ->
{custom,dict,true,dict:dict_to_list(D)};(_) -> no end).
true
4> v(1).
<|dict:[{3,a},{2,a},{5,a},{1,a},{4,a}]|>
5> xmerl_scan:string("<doc><title>Example doc</title><h1>chapter
1</h1><p>some text</p><h1>chapter 2</h1><p>some more text</p></doc>").
{{xmlElement,doc,  ....}}    % I'll spare you the agony
6> rr("/usr/local/lib/erlang/lib/xmerl-1.1.2/include/xmerl.hrl").
[xmerl_event,...]
7> fa(xmerl,fun(#xmlElement{}=E) ->
{custom,xml,true,xmerl_lib:simplify_element(E)}; (_) -> no end).
true
8> v(5).
{<|xml:{doc,[],
            [{title,[],["Example doc"]},
             {h1,[],["chapter 1"]},
             {p,[],["some text"]},
             {h1,[],["chapter 2"]},
             {p,[],["some more text"]}]}|>,
 []}

BR,
Ulf W
-------------- next part --------------
A non-text attachment was scrubbed...
Name: filter_funs.tgz
Type: application/x-gzip
Size: 15198 bytes
Desc: not available
URL: <http://erlang.org/pipermail/erlang-questions/attachments/20071110/13b396d9/attachment.bin>


More information about the erlang-questions mailing list