at:tutorial:metaprogramming
Differences
This shows you the differences between two versions of the page.
| Both sides previous revisionPrevious revision | |||
| at:tutorial:metaprogramming [2009/11/21 07:42] – added tvcutsem | at:tutorial:metaprogramming [2009/11/21 07:44] (current) – tvcutsem | ||
|---|---|---|---|
| Line 212: | Line 212: | ||
| ==== Multi-stage (Generative) Programming ==== | ==== Multi-stage (Generative) Programming ==== | ||
| - | Here's a small example of " | + | Here's a small example of " |
| Below is a regular power function. Given two numbers ' | Below is a regular power function. Given two numbers ' | ||
| - | < | + | < |
| def pow(x, n) { | def pow(x, n) { | ||
| if: (n == 0) then: { | if: (n == 0) then: { | ||
| Line 227: | Line 227: | ||
| Let's see whether it works: | Let's see whether it works: | ||
| - | < | + | < |
| system.println(pow(2, | system.println(pow(2, | ||
| </ | </ | ||
| Line 233: | Line 233: | ||
| Now, consider the following ' | Now, consider the following ' | ||
| - | < | + | < |
| def expandPow(var, | def expandPow(var, | ||
| if: (n == 0) then: { | if: (n == 0) then: { | ||
| Line 251: | Line 251: | ||
| To be able to use the expression generated by the above function, let's define a small helper function that will embed this expression in a first-class function: | To be able to use the expression generated by the above function, let's define a small helper function that will embed this expression in a first-class function: | ||
| - | < | + | < |
| def powMaker(n) { | def powMaker(n) { | ||
| def ast := expandPow(`x, | def ast := expandPow(`x, | ||
| Line 263: | Line 263: | ||
| Now we can generate power functions that are fixed in their second argument, but that are more efficient to execute: | Now we can generate power functions that are fixed in their second argument, but that are more efficient to execute: | ||
| - | < | + | < |
| // pow5 is now bound to a function { |x| x*x*x*x*x*1 } | // pow5 is now bound to a function { |x| x*x*x*x*x*1 } | ||
| def pow5 := powMaker(5); | def pow5 := powMaker(5); | ||
| Line 272: | Line 272: | ||
| You can measure the performance difference by timing the evaluation of both functions: | You can measure the performance difference by timing the evaluation of both functions: | ||
| - | < | + | < |
| import / | import / | ||
| system.println(" | system.println(" | ||
at/tutorial/metaprogramming.txt · Last modified: by tvcutsem
