3

以下是 O'Reilly Erlang 书中的一个练习:

构建操作算术表达式的函数集合。从如下表达式开始:

(~((2*3)+(3*4)))

它是完全括起来的,并且您使用波浪号 (~) 表示一元减号。

首先,为这些编写一个解析器,将它们转换为 Erlang 表示,例如:

{minus, {plus, {num, 2}, {num,3}}, {num, 4}}

这代表((2+3)-4) ...

我怎样才能做到这一点?

4

2 回答 2

3

好吧,你怎么做取决于你想要什么样的解析器。最简单的方法可能是使用yeccneotoma 之类的东西来为这种语言生成解析器。

如果您尝试手动编写解析器,那当然是可能的。以下是您开始编写的方法:

-module(parser).
-export([parse/1]).

%% parser:parse("((2+3)+4)") =:= {plus, {plus, {num, 2}, {num, 3}}, {num, 4}}.

parse(S) ->
    {[Expr], ""} = parse(S, expr, []),
    Expr.

-define(IS_DIGIT(C), (C >= $0 andalso C =< $9)).
-define(IS_SPACE(C),
        (C =:= $\s orelse C =:= $\t orelse C =:= $\r orelse C =:= $\n)).
is_space(C) ->
    ?IS_SPACE(C).
is_digit(C) ->
    ?IS_DIGIT(C).

skip_space(S) ->
    lists:dropwhile(fun is_space/1, S).

parse([$( | Rest], expr, []) ->
    {[Expr], Rest1} = parse(Rest, expr, []),
    [$) | Rest2] = skip_space(Rest1),
    parse(Rest2, op, [Expr]);
parse(S=[D | _], expr, []) when ?IS_DIGIT(D) ->
    {Ds, Rest1} = lists:splitwith(fun is_digit/1, S),
    parse(Rest1, op, [{num, list_to_integer(Ds)}]);
parse([$+ | Rest], op, [Left]) ->
    {[Right], Rest1} = parse(Rest, expr, []),
    {[{plus, Left, Right}], Rest1};
parse([C|Rest], State, Acc) when ?IS_SPACE(C) ->
    parse(skip_space(Rest), State, Acc);
parse(S, _State, Acc) ->
    {Acc, S}.
于 2013-09-02T04:04:38.880 回答
1

您可以查看我的代码以获得灵感: https ://github.com/pichi/epexercises/blob/master/Exercise3-8/e38.erl它使用手写词法分析器和解析器。还有用于堆栈机器代码和堆栈机器模拟器的编译器。

于 2013-09-05T22:32:57.183 回答