Sep 28, 2011

Splicing

The journey to macroland keeps amazing me!

Take splices. At first they seemed just a clever response to AST composability issue. Then I figured out that splices can be used to drastically simplify pattern matching. But even that didn't exhaust the bag of tricks provided by splices!

A few days after the pattern matching revelation, I learned how schemers use ellipses to write declarative syntax transformers. Say, we want to code up the following syntactic transformation: (let ([var val] ...) body) = ((lambda (var ...) body) val ...). Clear and concise, but imagine how ugly this will become when we'll try to transform this informal notation into executable code.

This problem has been addressed by Eugene Kohlbecker, a researcher from Scheme community. He extended the macro system to literally understand those ellipses:
(define-syntax my-let
  (syntax-rules ()
    [(my-let ([var val] ...) body)
      ((lambda (var ...) body) val ...)]))
Amazing, huh? But that still doesn't cover all the fancy uses of splices. For an icing on the cake, take a look at string interpolation example from Nemerle:
public static Render(this exprs : list[PExpr]) : String
{
  $<#..$(exprs; ", "; Render)#>
}

No comments:

Post a Comment