ERights Home elang / examples 
Back to: Examples from cs448 No Next Sibling

Multi-Stage Programming in E


? pragma.syntax("0.8")

? pragma.enable("easy-return")

? def EExpr := <type:org.erights.e.elang.evm.EExpr>

? def expandPow(xpr :EExpr, n :int) :EExpr {
>     if (n == 0) {
>         return e`1`
>     } else if (n == 1) {
>         return xpr
>     } else if (n %% 2 == 0) {
>         def xpr2 := expandPow(xpr, n//2)
>         return e`$xpr2 * $xpr2`
>     } else {
>         return e`$xpr * ${expandPow(xpr, n-1)}`
>     }
> }
# value: <expandPow>

? expandPow(e`x`, 5)
# value: e`x.multiply(x.multiply(x).multiply(x.multiply(x)))`

? def makePow(n :int) :any {
>     def powNExpr := e`def powN(x :int) :int {
>                          return ${expandPow(e`x`, n)}
>                      }`
>     return powNExpr.eval(safeScope)
> }
# value: <makePow>

? def pow5 := makePow(5)
# value: <powN>

? pow5(6)
# value: 7776

? 6**5
# value: 7776
 
Unless stated otherwise, all text on this page which is either unattributed or by Mark S. Miller is hereby placed in the public domain.
ERights Home elang / examples 
Back to: Examples from cs448 No Next Sibling
Download    FAQ    API    Mail Archive    Donate

report bug (including invalid html)

Golden Key Campaign Blue Ribbon Campaign