Skip to content

Instantly share code, notes, and snippets.

@yamasushi
Created December 4, 2023 22:32
Show Gist options
  • Save yamasushi/3c948fd6bdf49ea00058134544425bdd to your computer and use it in GitHub Desktop.
Save yamasushi/3c948fd6bdf49ea00058134544425bdd to your computer and use it in GitHub Desktop.
positive binary number
% positive binary number
% https://gist.github.com/yamasushi/3c948fd6bdf49ea00058134544425bdd
% Compilers 2nd ed. ex. 5.4.3 (p. 337)
-module(binnum).
-export([test/1]).
% B -> B1 0 { B.syn = 2 * B1.syn }
% | B1 1 { B.syn = 2 * B1.syn + 1}
% | 1 {B.syn = 1}
%
% B -> 1 {R.inh = 1} R {B.syn = R.syn}
% R -> 0 {R1.inh = R.inh * 2} R1 {R.syn = R1.syn}
% R -> 1 {R1.inh = R.inh * 2 + 1} R1 {R.syn = R1.syn}
% R -> ε {R.syn = R.inh}
b([$1|Rest]) -> r(1,Rest).
r(Inh,[])->[Inh,[]]; % ε
r(Inh,[$0|Rest]) -> r( Inh * 2 , Rest );
r(Inh,[$1|Rest]) -> r( Inh * 2 + 1 , Rest );
r(Inh,List) -> [Inh,List]. % ε
test(Num)->
[NumAns,Rest]=b(integer_to_list(Num,2)),
io:format("Num=~.2B(~w) , NumAns=~.2B(~w) , Rest=~w ~n"
,[Num,Num,NumAns,NumAns,Rest]).
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment