Andrew Cooke | Contents | Latest | RSS | 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

Choochoo Training Diary

Last 100 entries

Surprise Paradox; [Books] Good Author List; [Computing] Efficient queries with grouping in Postgres; [Computing] Automatic Wake (Linux); [Computing] AWS CDK Aspects in Go; [Bike] Adidas Gravel Shoes; [Computing, Horror] Biological Chips; [Books] Weird Lit Recs; [Covid] Extended SIR Models; [Art] York-based Printmaker; [Physics] Quantum Transitions are not Instantaneous; [Computing] AI and Drum Machines; [Computing] Probabilities, Stopping Times, Martingales; bpftrace Intro Article; [Computing] Starlab Systems - Linux Laptops; [Computing] Extended Berkeley Packet Filter; [Green] Mainspring Linear Generator; Better Approach; Rummikub Solver; Chilean Poetry; Felicitations - Empowerment Grant; [Bike] Fixing Spyre Brakes (That Need Constant Adjustment); [Computing, Music] Raspberry Pi Media (Audio) Streamer; [Computing] Amazing Hack To Embed DSL In Python; [Bike] Ruta Del Condor (El Alfalfal); [Bike] Estimating Power On Climbs; [Computing] Applying Azure B2C Authentication To Function Apps; [Bike] Gearing On The Back Of An Envelope; [Computing] Okular and Postscript in OpenSuse; There's a fix!; [Computing] Fail2Ban on OpenSuse Leap 15.3 (NFTables); [Cycling, Computing] Power Calculation and Brakes; [Hardware, Computing] Amazing Pockit Computer; Bullying; How I Am - 3 Years Post Accident, 8+ Years With MS; [USA Politics] In America's Uncivil War Republicans Are The Aggressors; [Programming] Selenium and Python; Better Walking Data; [Bike] How Fast Before Walking More Efficient Than Cycling?; [COVID] Coronavirus And Cycling; [Programming] Docker on OpenSuse; Cadence v Speed; [Bike] Gearing For Real Cyclists; [Programming] React plotting - visx; [Programming] React Leaflet; AliExpress Independent Sellers; Applebaum - Twilight of Democracy; [Politics] Back + US Elections; [Programming,Exercise] Simple Timer Script; [News] 2019: The year revolt went global; [Politics] The world's most-surveilled cities; [Bike] Hope Freehub; [Restaurant] Mama Chau's (Chinese, Providencia); [Politics] Brexit Podcast; [Diary] Pneumonia; [Politics] Britain's Reichstag Fire moment; install cairo; [Programming] GCC Sanitizer Flags; [GPU, Programming] Per-Thread Program Counters; My Bike Accident - Looking Back One Year; [Python] Geographic heights are incredibly easy!; [Cooking] Cookie Recipe; Efficient, Simple, Directed Maximisation of Noisy Function; And for argparse; Bash Completion in Python; [Computing] Configuring Github Jekyll Locally; [Maths, Link] The Napkin Project; You can Masquerade in Firewalld; [Bike] Servicing Budget (Spring) Forks; [Crypto] CIA Internet Comms Failure; [Python] Cute Rate Limiting API; [Causality] Judea Pearl Lecture; [Security, Computing] Chinese Hardware Hack Of Supermicro Boards; SQLAlchemy Joined Table Inheritance and Delete Cascade; [Translation] The Club; [Computing] Super Potato Bruh; [Computing] Extending Jupyter; Further HRM Details; [Computing, Bike] Activities in ch2; [Books, Link] Modern Japanese Lit; What ended up there; [Link, Book] Logic Book; Update - Garmin Express / Connect; Garmin Forerunner 35 v 230; [Link, Politics, Internet] Government Trolls; [Link, Politics] Why identity politics benefits the right more than the left; SSH Forwarding; A Specification For Repeating Events; A Fight for the Soul of Science; [Science, Book, Link] Lost In Math; OpenSuse Leap 15 Network Fixes; Update; [Book] Galileo's Middle Finger; [Bike] Chinese Carbon Rims; [Bike] Servicing Shimano XT Front Hub HB-M8010; [Bike] Aliexpress Cycling Tops; [Computing] Change to ssh handling of multiple identities?; [Bike] Endura Hummvee Lite II; [Computing] Marble Based Logic; [Link, Politics] Sanity Check For Nuclear Launch; [Link, Science] Entropy and Life

© 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