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

[Link, Programming] MySQL UTF8 Broken; NCOA for $20; [Link, Books] Latin American Authors; [Link, Computing] Optimizatin Puzzle; [Link, Books, Politics] Orwell Prize; [Link] What the Hell Is Happening With Qatar?; [Link] Deep Learning + Virtual Tensor Machines; [Link] Scaled Composites: Largest Wingspan Ever; [Link] SCP Foundation; [Bike] Lessons From 2 Leading 2 Trailing; [Link] Veg Restaurants in Santiago; [Link] List of Contemporary Latin American Authors; [Bike] FTHR; [Link] Whoa - NSA Reduces Collection (of US Residents); [Link] Red Bull's Breitbart; [Link] Linux Threads; [Link] Punycode; [Link] Bull / Girl Statues on Wall Street; [Link] Beautiful Chair Video; Update: Lower Pressures; [Link] Neat Python Exceptions; [Link] Fix for Windows 10 to Avoid Ads; [Link] Attacks on ZRTP; [Link] UK Jazz Invasion; [Review] Cuba; [Link] Aricle on Gender Reversal of US Presidential Debate; {OpenSuse] Fix for Network Offline in Updater Applet; [Link] Parkinson's Related to Gut Flora; Farellones Bike Park; [Meta] Tags; Update: Second Ride; Schwalbe Thunder Burt 2.1 v Continental X-King 2.4; Mountain Biking in Santiago; Books on Ethics; Security Fail from Command Driven Interface; Everything Old is New Again; Interesting Take on Trump's Lies; Chutney v6; References on Entropy; Amusing "Alexa.." broadcast; The Shame of Chile's Education System; Playing mp4 gifs in Firefox on Opensuses Leap 42.2; Concurrency at Microsoft; Globalisation: Uk -> Chile; OpenSuse 42.2 and Synaptics Touch-Pads; Even; Cherry Jam; Lebanese Writer Amin Maalouf; C++ - it's the language of the future; Learning From Trump; Chinese Writer Hu Fayun; And; Apricot Jam; Also; Excellent Article on USA Politics; Oh Metafilter; Prejudice Against The Rurals; Also, Zizek; Trump; Why Trump Won; Doxygen + Latex on CentOS 6; SMASH - Solve 5 Biggest Problems in Physics; Good article on racism, brexit, and social divides; Grandaddy are back!; Consciousness From Max Entropy; Democrats; Harvard Will Fix Black Poverty; Modelling Bicycle Wheels; Amusing Polling Outlier; If Labour keeps telling working class people...; Populism and Choice; Books on Defeat; Enrique Ferrari - Argentine Author; Transcript of German Scientists on Learning of Hiroshima; Calvert Journal; Owen Jones on Twitter; Possible Japanese Authors; Complex American Literature; Chutney v5; Weird Componentized Virus; Interesting Argentinian Author - Antonio Di Benedetto; Useful Thread on MetaPhysics; RAND on fighting online anarchy (2001); NSA Hacked; Very Good LRB Article on Brexit; Nussbaum on Anger; Tasting; Apple + Kiwi Jam; Hit Me; Sudoku - CSP + Chaos; Recycling Electronics In Santiago; Vector Displays in OpenGL; And Anti-Aliased; OpenGL - Render via Intermediate Texture; And Garmin Connect; Using Garmin Forerunner 230 With Linux; (Beating Dead Horse) StackOverflow; Current State of Justice in China; Axiom of Determinacy; Ewww; Fee Chaos Book

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