Necrobious'

Thursday, February 07, 2008

Abusing Erlang's Pattern Matching

I wrote a simple base62 encoder in erlang tonight. while it appears to be fast, I can't help but wonder if I'm abusing Erlang's pattern matching facilities.


-module(base62).
-export([encode/1, decode/1]).

encode(Num) ->
encode(Num, []).

encode(N,A) when N == 0 -> A;
encode(N,A) ->
encode(trunc(N/62), [e(N rem 62) |A]).

decode(S) ->
decode(lists:reverse(S),0,0).

decode([], V, _) -> V;
decode([H|T], V, D) ->
decode(T, V + (round(math:pow(62,D)) * d(H)), D+1).

e(0) ->$0; e(1) ->$1; e(2) ->$2;
e(3) ->$3; e(4) ->$4; e(5) ->$5;
e(6) ->$6; e(7) ->$7; e(8) ->$8;
e(9) ->$9; e(10) ->$a; e(11) ->$b;
e(12) ->$c; e(13) ->$d; e(14) ->$e;
e(15) ->$f; e(16) ->$g; e(17) ->$h;
e(18) ->$i; e(19) ->$j; e(20) ->$k;
e(21) ->$l; e(22) ->$m; e(23) ->$n;
e(24) ->$o; e(25) ->$p; e(26) ->$q;
e(27) ->$r; e(28) ->$s; e(29) ->$t;
e(30) ->$u; e(31) ->$v; e(32) ->$w;
e(33) ->$x; e(34) ->$y; e(35) ->$z;
e(36) ->$A; e(37) ->$B; e(38) ->$C;
e(39) ->$D; e(40) ->$E; e(41) ->$F;
e(42) ->$G; e(43) ->$H; e(44) ->$I;
e(45) ->$J; e(46) ->$K; e(47) ->$L;
e(48) ->$M; e(49) ->$N; e(50) ->$O;
e(51) ->$P; e(52) ->$Q; e(53) ->$R;
e(54) ->$S; e(55) ->$T; e(56) ->$U;
e(57) ->$V; e(58) ->$W; e(59) ->$X;
e(60) ->$Y; e(61) ->$Z.

d($0) -> 0; d($1) -> 1; d($2) -> 2;
d($3) -> 3; d($4) -> 4; d($5) -> 5;
d($6) -> 6; d($7) -> 7; d($8) -> 8;
d($9) -> 9; d($a) -> 10; d($b) -> 11;
d($c) -> 12; d($d) -> 13; d($e) -> 14;
d($f) -> 15; d($g) -> 16; d($h) -> 17;
d($i) -> 18; d($j) -> 19; d($k) -> 20;
d($l) -> 21; d($m) -> 22; d($n) -> 23;
d($o) -> 24; d($p) -> 25; d($q) -> 26;
d($r) -> 27; d($s) -> 28; d($t) -> 29;
d($u) -> 30; d($v) -> 31; d($w) -> 32;
d($x) -> 33; d($y) -> 34; d($z) -> 35;
d($A) -> 36; d($B) -> 37; d($C) -> 38;
d($D) -> 39; d($E) -> 40; d($F) -> 41;
d($G) -> 42; d($H) -> 43; d($I) -> 44;
d($J) -> 45; d($K) -> 46; d($L) -> 47;
d($M) -> 48; d($N) -> 49; d($O) -> 50;
d($P) -> 51; d($Q) -> 52; d($R) -> 53;
d($S) -> 54; d($T) -> 55; d($U) -> 56;
d($V) -> 57; d($W) -> 58; d($X) -> 59;
d($Y) -> 60; d($Z) -> 61.
Enjoy :)

1 Comments:

  • I don't know which is faster but i would probably write the following as it is clearer:

    e(C) when C >= 0, C =< 9 -> C + $0;
    e(C) when C >= 10, C =< 35 -> C - 10 + $a;
    e(C) when C >= 36, C =< 61 -> C - 36 + $A.

    At least I think so. :-)

    By Blogger Robert Virding, at 2:34 PM  

Post a Comment



<< Home