Skip to content

Instantly share code, notes, and snippets.

@hirotnk
Last active March 29, 2017 05:24
Show Gist options
  • Save hirotnk/c007f338cfc262482209bebb3c36a83c to your computer and use it in GitHub Desktop.
Save hirotnk/c007f338cfc262482209bebb3c36a83c to your computer and use it in GitHub Desktop.
parse_transeform example - from tlist to case statement
localhost [/home/yoshi_vagrant/egit%] erlc tlist_to_case.erl
localhost [/home/yoshi_vagrant/egit%] erlc -pa . +"{parse_transform,tlist_to_case}" tl_parset.erl
localhost [/home/yoshi_vagrant/egit%] cat case_statement.txt
do(Name) ->
case Name of
"US" ->
"001";
"GBP" ->
"002"
end.
localhost [/home/yoshi_vagrant/egit%] erl
Erlang/OTP 18 [erts-7.3] [source] [64-bit] [smp:8:8] [async-threads:10] [hipe] [kernel-poll:false]
Eshell V7.3 (abort with ^G)
1> tl_parset:do("US").
"001"
2> tl_parset:do("GBP").
"002"
3> tl_parset:do("Blah").
** exception error: no case clause matching "Blah"
in function tl_parset:do/1 (tl_parset.erl, line 6)
4>
-module(tl_parset).
-compile([{parse_transform, tlist_to_case}]).
-export([do/1]).
do(Name) -> {'$to_case',[{"US","001"},{"GBP","002"}]}.
-module(tlist_to_case).
-export([parse_transform/2]).
parse_transform(Forms, _Options) ->
Forms1 = lists:map(fun transform_to_case/1, Forms),
Forms1.
transform_to_case(
{function,L,do,1,
[{clause,_,
[{var,_,'Name'}],
[],
[{tuple,_,
[{atom,_,'$to_case'}, Tlist ]}]}]}) ->
Form =
{function,L,do,1,
[{clause,L,
[{var,L,'Name'}],
[],
[{'case',L,
{var,L,'Name'},
to_clause_list(Tlist,[]) }]}]},
file:write_file("case_statement.txt", erl_pp:form(Form)),
Form;
transform_to_case(Form) -> Form.
to_clause_list({nil,_L},Acc) -> lists:reverse(Acc);
to_clause_list({cons,_,{tuple,L,[K,V]},Tail}, Acc) -> to_clause_list(Tail, [{clause,L,[K],[],[V]}|Acc]).
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment