嗯,你怎么做取决于你想要什么样的解析器。最简单的方法可能是使用yecc 或neotoma 之类的东西来为这种语言生成解析器。
如果您尝试手动编写解析器,那当然是可能的。以下是您可以开始编写的方法:
-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}.