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

C-ORM: docs, API.

Last 100 entries

This Is Why I Left StackOverflow; New TLS Implementation; Maths for Physicists; How I Am 8; 1000 Word Philosophy; Cyberpunk Reading List; Detailed Discussion of Message Dispatch in ParserCombinator Library for Julia; FizzBuzz in Julia w Dependent Types; kokko - Design Shop in Osaka; Summary of Greece, Currently; LLVM and GPUs; See Also; Schoolgirl Groyps (Maths); Japanese Lit; Another Example - Modular Arithmetic; Music from United; Read Agatha Christie for the Plot; A Constructive Look at TempleOS; Music Thread w Many Recommendations; Fixed Version; A Useful Julia Macro To Define Equality And Hash; k3b cdrom access, OpenSuse 13.1; Week 2; From outside, the UK looks less than stellar; Huge Fonts in VirtualBox; Keen - Complex Emergencies; The Fallen of World War II; Some Spanish Fiction; Calling C From Fortran 95; Bjork DJ Set; Z3 Example With Python; Week 1; Useful Guide To Starting With IJulia; UK Election + Media; Review: Reinventing Organizations; Inline Assembly With Julia / LLVM; Against the definition of types; Dumb Crypto Paper; The Search For Quasi-Periodicity...; Is There An Alternative To Processing?; CARDIAC (CARDboard Illustrative Aid to Computation); The Bolivian Case Against Chile At The Hague; Clear, Cogent Economic Arguments For Immigration; A Program To Say If I Am Working; Decent Cards For Ill People; New Photo; Luksic And Barrick Gold; President Bachelet's Speech; Baltimore Primer; libxml2 Parsing Stream; configure.ac Recipe For Library Path; The Davalos Affair For Idiots; Not The Onion: Google Fireside Chat w Kissinger; Bicycle Wheels, Inertia, and Energy; Another Tax Fraud; Google's Borg; A Verion That Redirects To Local HTTP Server; Spanish Accents For Idiots; Aluminium Cans; Advice on Spray Painting; Female View of Online Chat From a Male; UX Reading List; S4 Subgroups - Geometric Interpretation; Fucking Email; The SQM Affair For Idiots; Using Kolmogorov Complexity; Oblique Strategies in bash; Curses Tools; Markov Chain Monte Carlo Without all the Bullshit; Email Para Matias Godoy Mercado; The Penta Affair For Idiots; Example Code To Create numpy Array in C; Good Article on Bias in Graphic Design (NYTimes); Do You Backup github?; Data Mining Books; SimpleDateFormat should be synchronized; British Words; Chinese Govt Intercepts External Web To DDOS github; Numbering Permutations; Teenage Engineering - Low Price Synths; GCHQ Can Do Whatever It Wants; Dublinesque; A Cryptographic SAT Solver; Security Challenges; Word Lists for Crosswords; 3D Printing and Speaker Design; Searchable Snowden Archive; XCode Backdoored; Derived Apps Have Malware (CIA); Rowhammer - Hacking Software Via Hardware (DRAM) Bugs; Immutable SQL Database (Kinda); Tor GPS Tracker; That PyCon Dongle Mess...; ASCII Fluid Dynamics; Brandalism; Table of Shifter, Cassette and Derailleur Compatability; Lenovo Demonstrates How Bad HTTPS Is; Telegraph Owned by HSBC; Smaptop - Sunrise (Music); Equation Group (NSA); UK Torture in NI; And - A Natural Extension To Regexps

© 2006-2015 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