"I have a mind like a steel... uh... thingy." Patrick Logan's weblog.

Search This Blog

Monday, September 10, 2007

List Comprehensions

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.

-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:

Anonymous said...

decode(String) ->
[[Char | Rest] ||
{Char, Code} <- codes(),
prefix(Code, String),
Rest <- decode(String -- Code)].

Blog Archive

About Me

Portland, Oregon, United States
I'm usually writing from my favorite location on the planet, the pacific northwest of the u.s. I write for myself only and unless otherwise specified my posts here should not be taken as representing an official position of my employer. Contact me at my gee mail account, username patrickdlogan.