[erlang-questions] Maze alternate example for Rosetta Code

Björn Gustavsson bjorn@REDACTED
Sun Feb 14 11:38:48 CET 2016


On Fri, Feb 12, 2016 at 4:31 PM, Bill Durksen <bdurksen@REDACTED> wrote:
>
> 2. 114 packed lines of Erlang code just seems to over-coded for such a
> powerful language.
>     Not being an expert, yet, in all the nuances of Erlang, can someone
> suggest ways I can decrease maze.erl code down to 99 lines or less, without
> cheating (removing too many newlines)?

Here are few pointers for more idiomatic Erlang.

Most of the time you want to use 'case' and not 'if'.
Your code:

has_neighbour(Maze, Row, Col, Direction) ->
    V = vertex_at(Row, Col, Maze),
    if
        V >= 0 ->
            Adjacent = adjacent_cell(Direction, V, Maze),
            if
                length(Adjacent) > 0 ->
                    Neighbours = digraph:out_neighbours(Maze#maze.g,
lists:nth(1, Adjacent)),
                    lists:member(V, Neighbours);
                true -> false
            end;
        true -> false
    end.

This can be rewritten to:

has_neighbour(Maze, Row, Col, Direction) ->
    case vertex_at(Row, Col, Maze) of
        V when V >= 0 ->
            case adjacent_cell(Direction, V, Maze) of
                [Adjacent] ->
                    Neighbours = digraph:out_neighbours(Maze#maze.g, Adjacent),
                    lists:member(V, Neighbours);
                [] -> false
            end;
        _ -> false
    end.

I also used pattern matching to avoid using length/1
and lists:nth/1.

Another example. Here is your code:

vertex_at(Row, Col, Maze) -> Cell_Exists = cell_exists(Row, Col,
Maze), if Cell_Exists -> Row * Maze#maze.n + Col; true -> -1 end.

You return -1 if there is no vertex. More idiomatic Erlang would be:

vertex_at(Row, Col, Maze) ->
  case cell_exists(Row, Col, Maze) of
     true -> Row * Maze#maze.n + Col;
     false -> none
  end.

or:

vertex_at(Row, Col, Maze) ->
  case cell_exists(Row, Col, Maze) of
     true -> {ok,Row * Maze#maze.n + Col};
     false -> error
  end.

/Björn

-- 
Björn Gustavsson, Erlang/OTP, Ericsson AB



More information about the erlang-questions mailing list