Erlang Records печать - PullRequest
       38

Erlang Records печать

1 голос
/ 01 мая 2020

Я пишу программу на эрланге, и я создал эту запись:

-record(tree, {node, left, right}).

Я хочу напечатать список различных деревьев, и вот как это печатается:

[{tree,x1,{x3,0,1},{tree,x2,1,{x3,0,1}}}, {tree,x1,{tree,x3,0,1},{tree,x3,{x2,1,0},1}}]

Есть ли легко распечатать его без слова «дерево»? (название записи). Конечно, я могу определить это как кортеж, а не запись, но я хочу попробовать работать с записью, чтобы код был более организованным.

1 Ответ

1 голос
/ 02 мая 2020

Да, есть. Внутри оболочки вы можете использовать:

Eshell V9.1  (abort with ^G)
1> Trees = [
    {tree, x1, {x3, 0, 1}, {tree, x2, 1, {x3, 0, 1}}},
    {tree, x1, {tree, x3, 0, 1}, {tree, x3, {x2, 1, 0}, 1}}
].

[{tree,x1,{x3,0,1},{tree,x2,1,{x3,0,1}}},{tree,x1,{tree,x3,0,1},{tree,x3,{x2,1,0},1}}]


2> Format = fun({tree, Node, Left, Right}, F) -> 
    {
        Node,
        if 
            element(1, Left) == tree -> F(Left, F);
            true -> Left
        end,
        if
            element(1, Right) == tree -> F(Right, F);
            true -> Right
        end
    }
end.
#Fun<erl_eval.12.99386804>

3> [Format(X, Format) || X <- Trees].
[
    {{x3, 0, 1}, {1, {x3, 0, 1}}},
    {{0, 1}, {{x2, 1, 0}, 1}}
]

И в вашем модуле вы можете разместить, например, функцию format/1:

-module(tree).

-record(tree, {node, left, right}).

-export([format/1]).


format(#tree{node = Node, left = L, right = R}) ->
    {Node, maybe_format(L), maybe_format(R)};

format([#tree{}=Tree | Trees]) ->
    [format(Tree) | format(Trees)];

format([]) ->
    [].


maybe_format(X) when erlang:is_record(X, tree) ->
    format(X);

maybe_format(X) ->
    X.

И использовать ее в оболочке или где угодно хочу:

Eshell V9.1  (abort with ^G)
% Compile my module which is inside current directory:
1> c(tree).
{ok,tree}

% format single tree:
2> tree:format({tree, node, left, right}).
{node,left,right}

% format list of trees:
3> tree:format([{tree,x1,{x3,0,1},{tree,x2,1,{x3,0,1}}}, {tree,x1,{tree,x3,0,1},{tree,x3,{x2,1,0},1}}]).

[
    {x1, {x3, 0, 1}, {x2, 1, {x3, 0, 1}}},
    {x1, {x3, 0, 1}, {x3, {x2, 1, 0}, 1}}
]
...