| Andrew Cooke | Contents | Latest | RSS | Twitter | Previous | Next

C[omp]ute

Welcome to my blog, which was once a mailing list of the same name and is still generated by mail. Please reply via the "comment" links.

Always interested in offers/projects/new ideas. Eclectic experience in fields like: numerical computing; Python web; Java enterprise; functional languages; GPGPU; SQL databases; etc. Based in Santiago, Chile; telecommute worldwide. CV; email.

Personal Projects

Lepl parser for Python.

Colorless Green.

Photography around Santiago.

SVG experiment.

Professional Portfolio

Calibration of seismometers.

Data access via web services.

Cache rewrite.

Extending OpenSSH.

Last 100 entries

Ky - Restaurant Santiago; The Black Dork Lives!; The UN Requires Unaninmous Decisions; LPIR - Steganography in Practice; How I Am 6; Clear Explanation of Verizon / Level 3 / Netflix; Teenage Girls; Formalising NSA Attacks; Switching Brakes (Tektro Hydraulic); Naim NAP 100 (Power Amp); AKG 550 First Impressions; Facebook manipulates emotions (no really); Map Reduce "No Longer Used" At Google; Removing RAID metadata; New Bike (Good Bike Shop, Santiago Chile); Removing APE Tags in Linux; Compiling Python 3.0 With GCC 4.8; Maven is Amazing; Generating Docs from a GitHub Wiki; Modular Shelves; Bash Best Practices; Good Emergency Gasfiter (Santiago, Chile); Readings in Recent Architecture; Roger Casement; Integrated Information Theory (Or Not); Possibly undefined macro AC_ENABLE_SHARED; Update on Charges; Sunburst Visualisation; Spectral Embeddings (Distances -> Coordinates); Introduction to Causality; Filtering To Help Colour-Blindness; ASUS 1015E-DS02 Too; Ready Player One; Writing Clear, Fast Julia Code; List of LatAm Novels; Running (for women); Building a Jenkins Plugin and a Jar (for Command Line use); Headphone Test Recordings; Causal Consistency; The Quest for Randomness; Chat Wars; Real-life Financial Co Without ACID Database...; Flexible Muscle-Based Locomotion for Bipedal Creatures; SQL Performance Explained; The Little Manual of API Design; Multiple Word Sizes; CRC - Next Steps; FizzBuzz; Update on CRCs; Decent Links / Discussion Community; Automated Reasoning About LLVM Optimizations and Undefined Behavior; A Painless Guide To CRC Error Detection Algorithms; Tests in Julia; Dave Eggers: what's so funny about peace, love and Starship?; Cello - High Level C Programming; autoreconf needs tar; Will Self Goes To Heathrow; Top 5 BioInformatics Papers; Vasovagal Response; Good Food in Vina; Chilean Drug Criminals Use Subsitution Cipher; Adrenaline; Stiglitz on the Impact of Technology; Why Not; How I Am 5; Lenovo X240 OpenSuse 13.1; NSA and GCHQ - Psychological Trolls; Finite Fields in Julia (Defining Your Own Number Type); Julian Assange; Starting Qemu on OpenSuse; Noisy GAs/TMs; Venezuela; Reinstalling GRUB with EFI; Instructions For Disabling KDE Indexing; Evolving Speakers; Changing Salt Size in Simple Crypt 3.0.0; Logarithmic Map (Moved); More Info; Words Found in Voynich Manuscript; An Inventory Of 3D Space-Filling Curves; Foxes Using Magnetic Fields To Hunt; 5 Rounds RC5 No Rotation; JP Morgan and Madoff; Ori - Secure, Distributed File System; Physical Unclonable Functions (PUFs); Prejudice on Reddit; Recursion OK; Optimizing Julia Code; Cash Handouts in Brazil; Couple Nice Music Videos; It Also Works!; Adaptive Plaintext; It Works!; RC5 Without Rotation (2); 8 Years...; Attack Against Encrypted Linux Disks; Pushing Back On NSA At IETF; Summary of Experimental Ethics; Very Good Talk On Security, Snowden; Locusts are Grasshoppers!; Vagrant (OpenSuse and IDEs)

© 2006-2013 Andrew Cooke (site) / post authors (content).

Lazy Resolution of Circular Dependencies in an Eager Language

From: "andrew cooke" <andrew@...>

Date: Fri, 11 May 2007 21:05:53 -0400 (CLT)

I guess this is well known, but I just invented it myself, so think it's
neat!

I have a parser defined as a set of inter-related parser combinators
(PCs).  Each PC is "constructed" by calling a "builder" that takes other
PC "constructors" (keep reading - I explain all this below).

So, for example, in

comment(Semicolon, Wsp, VChar, CrLf) ->
    all([Semicolon, star(either(Wsp, VChar)), CrLf]).

comment() -> comment(semicolon(), wsp(), v_char(), cr_lf()).

the first function is a builder - it describes how to build a parser for
comments if you have a parser for semicolons, whitespaces, etc.  The
second function is a constructor that actually does build you a PC and
does so using specific PCs that it calls (semicolon() generates a
particular parser for semicolons, etc).

A PC is a function that takes a string and returns a parsed version -
typically an abstract syntax tree.  So if I executed the code above I
might see:

> MyCommentParser = comment().               % construct the PC
> MyCommentParser("; this is a comment~n").  % do the parsing
{comment, "this is a comment"}

where the parser has generated a tuple containing a label ('comment') and
a value ("this is a comment").  You can imagine that a parser for a
program gives a much more complex set of lists and tuples that form a
complex tree describing the program.

Obviously there's a top-level PC for the whole program.  In this case it's
called "rulelist".  And there are PCs for all the "intermediate"
representations - things like "rulename", "element", "group",
"repetition".

So far, so good.

BUT, unfortunately, the language can define elements that are groups of
elements.  More exactly, it turns out that there are "alternations" of
both "groups" and "options".

This means I have constructors something like:

alternation() -> alternation(concatenation(), c_wsp(), slash()).
concatenation() -> concatenation(repetition(), c_wsp()).
repetition() -> repetition(repeat(), element()).
element() -> element(rulename(), group(), option(), ...).
group() -> group(open_paren(), c_wsp(), alternation(), close_paren()).
option() ->
  option(open_bracket(), c_wsp(), alternation(), close_bracket()).

(don't confuse the builders and the constructors - functions with
different numbers of arguments are completely distinct in Erlang).

Spot the problem?  What happens when I call alternation()?

Well, alternation() calls concatenation(), which calls repetition(), which
calls...  group() which calls alternation() which calls ...

It's an infinite loop.

This is what I was referring to in my previous post.

And at first I didn't have a clue how to fix this.  The code above is very
close to the text of RFC 2234 - http://www.ietf.org/rfc/rfc2234.txt - and
I don't want to change it much, because the closer it is to the
specification the more chance I have that it is going to work as expected.


My best solution uses the following insight: in reality we never need an
infinite loop.  Any finite text, when parsed, will only have some finite
level of nested elements.  So I could just define some arbitrary limit
(ugly) or I could make the code "lazy" so that it only grows when needed.

That wasn't enough, though, because I always thought of laziness as
requiring mutable state: you define a "thunk" that pretends to be the
function, and is updated when needed to "really be" the function.  That
update seems to need mutable state - you are changing something.  And
Erlang doesn't have (easy to use) mutable state.

But then I realised I could just shift when the function is evaluated!

A PC is a function that returns something when it's given a string.  So
until it's given a string, we don't need it.  So why not create the
function only when that string is given?

Here's the code:

alternation() ->
    fun(Stream) ->
            alternation(concatenation(), c_wsp(), slash())
    end.

Nothing else needs to change.  It works - the parser runs fine. :o)

So all you need for laziness is higher order functions.  And, in a way,
this only works because I am using "empty" function evaluation instead of
values, which was forced on me by Erlang's module system.  Inside ever
cloud is a silver lining...

Andrew

Inefficient, but that's OK

From: "andrew cooke" <andrew@...>

Date: Fri, 11 May 2007 21:27:25 -0400 (CLT)

The solution above is inefficient, but that's OK - this code is only to
bootstrap an automated generator for these things.  And I think that can
use it's own "namespace" to solve this problem - basically each PC takes a
hashtable from which it pulls other PCs by name, as needed.

I hope.

Andrew

CPS!

From: "andrew cooke" <andrew@...>

Date: Fri, 11 May 2007 21:53:47 -0400 (CLT)

Another way to look at the the above (the "namespace") is that it collects
all the functions together so that you can convert everything to
continuation passing style.  This exploits tail call recursion. and avoids
spawning new functions to handle cycles.

My head is spinning, a bit, but I think that's right.

Andrew

Correction

From: "andrew cooke" <andrew@...>

Date: Fri, 11 May 2007 22:57:25 -0400 (CLT)

I just noticed that the original post had an incorrect early version of
the code in the final solution.  It should be:

alternation() ->
    fun(Stream) ->
            apply(alternation(concatenation(), c_wsp(), slash()), [Stream])
    end.

The initial version "loses" Stream (which gives a compiler warning - those
are very useful) and returns an unevaluated function.

Andrew

Comment on this post