@@ -62,29 +62,34 @@ in class `Expr` called `run`. Note that `$` and `run` both map from `Expr[T]`
62
62
to ` T ` but only ` $ ` is subject to the PCP, whereas ` run ` is just a normal method.
63
63
64
64
``` scala
65
- sealed abstract class Expr [T ] {
66
- def run given (toolbox : Toolbox ): T // run staged code
67
- def show given (toolbox : Toolbox ): String // show staged code
68
- }
65
+ package scala .quoted
66
+
67
+ def run [T ](expr : given QuoteContext => Expr [T ]) given (toolbox : Toolbox ): T = ...
69
68
```
70
69
71
70
## Example
72
71
73
72
Now take exactly the same example as in [ Macros] ( ./macros.html ) . Assume that we
74
73
do not want to pass an array statically but generated code at run-time and pass
75
74
the value, also at run-time. Note, how we make a future-stage function of type
76
- ` Expr[Array[Int] => Int] ` in line 4 below. Invoking the ` .show ` or ` .run ` we can
75
+ ` Expr[Array[Int] => Int] ` in line 4 below. Using ` run { ... } ` we can evaluate an
76
+ expression at runtime. Within the scope of ` run ` we can also invoke ` show ` on an expression
77
+ to get
78
+
79
+ Invoking the ` .show ` or ` .run ` we can
77
80
either show the code or run it respectivelly.
78
81
79
82
``` scala
80
83
// make available the necessary toolbox for runtime code generation
81
84
implicit val toolbox : scala.quoted.Toolbox = scala.quoted.Toolbox .make(getClass.getClassLoader)
82
85
83
- val stagedSum : Expr [Array [Int ] => Int ] = ' { (arr : Array [Int ]) => $ {sum(' arr )}}
84
-
85
- println(stagedSum.show)
86
+ val f : Array [Int ] => Int = run {
87
+ val stagedSum : Expr [Array [Int ] => Int ] = ' { (arr : Array [Int ]) => $ {sum(' arr )}}
88
+ println(stagedSum.show) // Prints "(arr: Array[Int]) => { var sum = 0; ... }"
89
+ stagedSum
90
+ }
86
91
87
- stagedSum.run .apply(Array (1 , 2 , 3 )) // Returns 6
92
+ f .apply(Array (1 , 2 , 3 )) // Returns 6
88
93
```
89
94
90
95
Note that if we need to run the main (in an object called ` Test ` ) after
0 commit comments