β

Infix Translator Erlang Implementation

./Lu 7 阅读

I read a little about Erlang last year, but due to some reason I didn’t acquire the details, just skimmed through the textbook. When i started to implement a compiler lately, the thought that Erlang might be very suitable for doing this came to me immediately.

I’m not familiar with Erlang, even not a newbie, this article is just for introducing the idea of applying pattern matching to compiler implementation, and the code have much to improve.

Consider the snippet below which is an excerpt from an infix-to-postfix translator .

% Simple infix to postfix translator for the grammar:
%
%  expr -> term rest
% 
%  term -> 0       {print 0}
%       | 1        {print 1}
%       | 2        {print 2}
%       | 3        {print 3}
%       ... 
%       | 9        {print 9}
% 
%  rest -> + term rest    {print +}
%       |  - term rest    {print -}
%       |  Ɛ

term([Peek|_]) ->
  num(Peek).

rest([Peek|T]) ->
  term(T),
  op(Peek),
  [_|Rest] = T,
  rest(Rest).

num(Peek) when Peek >= 48, Peek =< 57 ->
  io:format("~c ", [Peek]).

op(Peek) when Peek == 43; Peek == 45 ->
  io:format("~c ", [Peek]).

Since scanning and tokenizing is basically matching strings, with complicate switching conditions. It’s very alike to what Erlang’s pattern matching does. And if the complex conditions are written with Erlang’s guards syntax, that would be much more readable than written in a clutter of switch es or if s.

While scanning, one char is readahead once a time to determine whether current token is ended or not. With Erlang, this is just as simple as [Peek|T] = Content .

Erlang’s function guards come in handy when there’re a lot of conditions like deciding token type, which is not shown above yet in that simple task. I’ll try to implement a complete scanner with Erlang later.

The nature of a top-down recursive-decent parser is recursion, which suits Erlangs functional pattern well. Since the language is designed to do so, it’s more comfortable to write recursion in Erlang.

I believe the code can be shorter and more readable with another language, but Erlang’s feature is more suitable for doing this. Every line maps to the grammar design, like Erlang was designed for implementing a parser.

There’re also something I found not so pretty. Erlang’s compiler seems to do less static checking than other compilers, causing more time cost for debugging. I have to use Erlang shell every time to type infix_translator:translate({"1+2+3", string}) to try my program out. But this shouldn’t be a problem, there must be a better way which I haven’t found. I’ve heard using emacs could be more convenient than using vim to write Erlang.

I’m growing more and more fond of Erlang.

作者:./Lu
Better now than later.Better late than never.
原文地址:Infix Translator Erlang Implementation, 感谢原作者分享。

发表评论