Start of topic | Skip to actions

An Introduction to Staging in Concoqtion

let rec power m n =
  if n =  0 then 1
  else power m (n - 1) * m;;

power 2 3 = 2 * 2^2
 = 2 * (2 * 2^1)
 = 2 * (2 * (2 * 1))

Look at the square function:

let square x = power x 2;;
this function is specialized for use, but in terms of performance, there is no difference. Every time you call it, you will be recursively unrolling the power function;;

compare this to:

let square2 x = x * x;;
This is a much better version

Above when we call "power x 2" we already know one of the arguments (2 is constant). We want to be able to generate a:

lambda x.x*x

when n = 2, or

lambda x.x*x*x
when n = 3. We can generate these as strings.

Multi-staged programming lets you write functions like these lambdas, but not as strings.

type: 'a code
.< exp >.
( .< 2 + 3 >. ) : int code

These are well typed versions of the strings we tried to generate above.

let e = .<2 + 3>.
  in <.~e * .~e>

This is equal to

< (2 + 3) * (2 + 3) >

or to generate the string equivalent:

sprintf "%s * %s" e1 e1;;

The .~ operator is called an "escape." The typing rules for brackets and escapes are as follows:

\gamma \turn(n+1) e : t
-------------------------
\gamma \turn(n) <e> : t code

The count n is used to keep track of how many brackets we are inside of.

\gamma \turn(n) e : t code
-------------------------
\gamma \turn(n+1) ~e : t

Can we handle:

<lambda x. ~(print x; <0>)>

No! x can not be accessed from within the escape. Think of it as a string:

("lambda x." ^ (print x; "0"))

Does this make sense:

<lambda x. ~(print 0; <x>)>

Yes! We need to update our typing rules to handle variables correctly:

\gamma, x:t1(n) \turn(n) e:t2
-------------------
\gamma \turn(n) lambda x.e : t1 -> t2


x : t(m) \elementOf \gamma s.t. n > m
-------------------
\gamma \turn(n) x:t

A run construction is: .!e

\empty \turn(n) e: t code
-------------------
\gamma \turn(n) !e : t

This requires that e can be typed in an empty environment

Check out the paper introducing staged programming.


End of topic
Skip to actions | Back to top
Creative Commons LicenseThis work is licensed under a Creative Commons Attribution 2.5 License. Please follow our citation guidelines.