Merlyn Albery-Speyer rewrote my morse code example using erlang's list comprehensions. It's posted on the pdx.erl site. Here I have reproduced it but I'm using the same variable names from my earlier example to make the comparison easier on the eye.
It's doing essentially the same thing in fewer lines of code because the list comprehension syntax is so concise. Not that the previous example was so long in the first place, but coming from an older Lisp world where we wrote out our recursions in "long form" ;-/, I need to remember to keep list comprehensions in my toolkit.
-module(lcmorse).
-export([codes/0, decode/1]).
-import(lists, [prefix/2, reverse/1]).
-import(string, [len/1, substr/2]).
codes() ->
[{$A, ".-"}, {$B, "-..."}, {$C, "-.-."}, {$D, "-.."}, {$E, "."},
{$F, "..-."}, {$G, "--."}, {$H, "...."}, {$I, ".."}, {$J, ".---"},
{$K, "-.-"}, {$L, ".-.."}, {$M, "--"}, {$N, "-."}, {$O, "---"},
{$P, ".--."}, {$Q, "--.-"}, {$R, ".-."}, {$S, "..."}, {$T, "-"},
{$U, "..-"}, {$V, "...-"}, {$W, ".--"}, {$X, "-..-"}, {$Y, "-.--"},
{$Z, "--.."}].
decode("") -> [""];
decode(String) ->
[[Char | Rest] ||
{Char, Code} <- codes(),
prefix(Code, String),
Rest <- decode(substr(String, 1 + len(Code)))].
1 comment:
decode(String) ->
[[Char | Rest] ||
{Char, Code} <- codes(),
prefix(Code, String),
Rest <- decode(String -- Code)].
Post a Comment