Writing a DSL with Python
blog.fmeyer.org
blog.fmeyer.org
Some links:
1. O'Reilly mini-book on pyparsing (probably best single ref) http://oreilly.com/catalog/9780596514235/
2. Quick example of pyparsing http://eikke.com/pyparsing-introduction-bnf-to-code/
3. Main pyparsing page (i know it's not very aesthetically pleasing. The code is much better, I promise) http://pyparsing.wikispaces.com/
4. Links to more on pyparsing here http://pyparsing.wikispaces.com/Publications
Python Magazine is excellent, by the way. Definitely worth the purchase price as they include a zip file with code. (Mandatory disclaimer: I have no stake in it at all. Just found it very useful, that's all).
ref: http://www.bofh.org.uk/2007/08/08/domain-specific-pidgin
It uses python itself as a DSL to make things like packet forging easy:
>>> Ether()/IP()/TCP()/"GET / HTTP/1.0\r\n\r\n"
<Ether type=0x800 |IP frag=0 proto=TCP |<TCP |<Raw load='GET / HTTP/1.0\r\n\r\n' |>>>>
Here the / operator was overloaded to stack layers.(See point-free style.)
def doSomething():
def doSomethingElse():
# Code goes here.
pass
eggs = filter(doSomethingElse, spam)
for cheese in eggs:
# Do something.
passI really don't get why some people hate the indention-as-syntax. Sure, its different to C and Java, but it also results in (more) consistently formatted code and readable indention. It also only takes a day or two to get used to, even if you're a hardened C++ user (for the record, I have nothing against C/C++ syntax, I actually switched from years of C++ to Python as my main language and I just recently started a C++/Python hybrid project).
# value x =[|1;2;3;4|];
value x : array int = [|1; 2; 3; 4|]
# for i = 0 to (Array.length x) - 1 do {
Printf.printf "%d" x.(i);
};
1234- : unit = ()
# Array.iter (fun y -> Printf.printf "%d" y) x;
1234- : unit = ()
Basically the entire body of any for loop I would want to make an anonymous function. Then if I cared about the result I could do: # Array.map (fun y -> Printf.printf "%d" y) x;
1234- : array unit = [|(); (); (); ()|]
Assuming the underlying platform supported it, and the function is pure, that's "free" parallelism.