quiz about symbolic manipulation

holger krekel pyth at devel.trillke.net
Tue Dec 17 09:40:33 EST 2002


Bengt Richter wrote:
> On Mon, 16 Dec 2002 14:24:59 GMT, Michael Hudson <mwh at python.net> wrote:
> 
> >bokr at oz.net (Bengt Richter) writes:
> >
> >> Well, for a toy problem, parsing according to python grammar is probably
> >> overkill. I.e.,
> >> 
> >> 'square(square(x+y)+z)+square(x+w)'
> >> 
> >> becomes
> >> 
> >> ['eval_input',
> >>  ['testlist',
> >>   ['test',
> >>    ['and_test',
> >>     ['not_test',
> >>      ['comparison',
> >>       ['expr',
> >>        ['xor_expr',
> >[... and on and on and on ...]
> >
> >Bengt probably knows this, but you can use the compiler package to
> >make this very much pleasanter...
> >
> Christmas is here early ;-)
> 
> >>>> compiler.transformer.parse('square(square(x+y)+z)+square(x+w)')
> >Module(None, Stmt([Discard(Add((CallFunc(Name('square'),
> >[Add((CallFunc(Name('square'), [Add((Name('x'), Name('y')))], None,
> >None), Name('z')))], None, None), CallFunc(Name('square'),
> >[Add((Name('x'), Name('w')))], None, None))))]))
> >>>> _.node.nodes[0].expr
> >Add((CallFunc(Name('square'), [Add((CallFunc(Name('square'),
> >[Add((Name('x'), Name('y')))], None, None), Name('z')))], None, None),
> >CallFunc(Name('square'), [Add((Name('x'), Name('w')))], None, None)))
> >
> >Hmm, well the fact that pprint.pprint doesn't know how to deal with
> >these thigns doesn't help, but these really are nicer to work with :)
> >
> How about this as relatively simple prettyprinting for this kind of output?
> [ 5:49] C:\pywk\clp>ppcomp.py -h
> 
> Usage:  python ppcomp.py [-i | -h | -f filename | expression ]
>         (nothing specified reads stdin, -i prompts, -h prints this, else the obvious)
> 
> 
> [ 5:49] C:\pywk\clp>ppcomp.py square(square(x+y)+z)+square(x+w)
> Module(
>   None,
>   Stmt(
>     [
>       Discard(
>         Add(
>           (
>             CallFunc(
>             | Name(
>             | | 'square'),
>             | [
>             | | Add(
>             | |   (
>             | |     CallFunc(
>             | |     | Name(
>             | |     | | 'square'),
>             | |     | [
>             | |     | | Add(
>             | |     | |   (
>             | |     | |     Name(
>             | |     | |     | 'x'),
>             | |     | |     Name(
>             | |     | |       'y')))],

hey, this begins to look like lisp!  :-)
nice utility, btw.  

    holger





More information about the Python-list mailing list