[Top][All Lists]

[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]

Re: Defining Functions With Syntax

From: Mark H Weaver
Subject: Re: Defining Functions With Syntax
Date: Wed, 21 Sep 2011 12:12:23 -0400
User-agent: Gnus/5.13 (Gnus v5.13) Emacs/23.3 (gnu/linux)

Andy Wingo <address@hidden> writes:
> On Tue 20 Sep 2011 21:00, Noah Lavine <address@hidden> writes:
>> The PEG documentation recommends doing '(eval `(define-nonterm as body
>> ,exp) (interaction-environment))', where 'exp' is whatever your
>> s-expression is. This seems like a bad idea to me, because a) it also
>> defines a variable 'as', which is not needed and maybe not what you
>> want and b) it seems unnecessarily complicated.
> Regarding the first, you can `(let () (define-nonterm as body ,exp) as)'
> or something, in which the `as' definition doesn't leak beyond that
> inner lexical contour.
> It is complicated though.  The other option is to write a PEG
> interpreter or compiler in Scheme.  An interpreter would interpret the
> s-expressions directly, or some simplified form of them.  A compiler
> would pre-process the s-expressions to produce a procedure, built from
> closures.
> For example here is a simple matcher that matches pairs:
>   (use-modules (system base pmatch))
>   (define (make-pair-matcher pat)
>     (pmatch pat
>       ((head . tail)
>        (let ((hmatch (make-pair-matcher head))
>              (tmatch (make-pair-matcher tail)))
>          (lambda (x)
>            (and (pair? x) (hmatch (car x)) (tmatch (cdr x))))))
>       (datum
>        (lambda (x) (eq? x datum)))))
>   ((make-pair-matcher '(foo . bar)) '(foo . bar))
>   => #t
> I say that this is "compiled" because the matcher code is wired together
> from closures, whose code is compiled, and matching against a datum
> doesn't dispatch against the pattern at runtime: that path is computed
> (compiled) already by the `make-pair-matcher' procedure.

It occurs to me that, with a sufficiently powerful peval, a PEG compiler
written in the above style could be the only implementation we need.

If the s-expression is a compile-time constant, and if the PEG compiler
is written in purely-functional style and confined within a single
top-level form, then peval should be able to produce the parser
procedure at compile-time.  Otherwise, it would be produced at run-time.

This is part of the reason partial evaluation is so exciting.  It's not
just about increasing the speed of existing programs.  More importantly,
it allows you to write new programs more elegantly.


reply via email to

[Prev in Thread] Current Thread [Next in Thread]