Wednesday, May 25, 2005
Tuesday, May 24, 2005
Argument order
For multiple-arity functions, it would be more abstract to pass arguments by label rather than order. Just like pattern matching is more abstract than using explicit selectors, passing in arguments by label allows you to pass arguments in any order, and would allow for a more general form of currying. It would also simplify partial evaluation, since you wouldn't have to rearrange a function's arguments to apply it to a subset of them.
Nevertheless, tuples are a lighter-weight data structure than records, and lighter-weight solutions are easier to write and often easier to read. Positional function arguments are here to stay.
Because the order of arguments isn't always particularly relevant, the order can seem arbitrary. As the designer of a procedure, it's sometimes hard to know what order to choose. Here's one criterion: think about currying. It can be useful to put the arguments expected to be known earlier before the arguments expected to be known later.
For example, in Syntactic Abstraction in Scheme, the heart of the definition of the macro expansion algorithm is the rule for macro applications:
There's a functional pipeline buried in that rule, but it's obscured by the order of arguments. This is actually a good candidate for point-free style. Since we expect the environment argument r for expand to be known before the expression, and the mark argument m for mark to be known before the expression argument, let's swap the order of arguments to both those functions. Now we get the new rule
Nevertheless, tuples are a lighter-weight data structure than records, and lighter-weight solutions are easier to write and often easier to read. Positional function arguments are here to stay.
Because the order of arguments isn't always particularly relevant, the order can seem arbitrary. As the designer of a procedure, it's sometimes hard to know what order to choose. Here's one criterion: think about currying. It can be useful to put the arguments expected to be known earlier before the arguments expected to be known later.
For example, in Syntactic Abstraction in Scheme, the heart of the definition of the macro expansion algorithm is the rule for macro applications:
expand(e, r) =This is pretty hard to read. Without getting too much into the specific details of the algorithm, the idea of this rule is that to expand a macro application, you mark the expression with a fresh mark, apply the macro transformer t to the marked expression, then mark the output of that transformer again with the same mark, and finally expand the result.
case parse(e, r) of
...
macro-application(i, e) → expand(mark(t(mark(e, m)), m), r)
where t = r(resolve(i)) and m is fresh
There's a functional pipeline buried in that rule, but it's obscured by the order of arguments. This is actually a good candidate for point-free style. Since we expect the environment argument r for expand to be known before the expression, and the mark argument m for mark to be known before the expression argument, let's swap the order of arguments to both those functions. Now we get the new rule
...
macro-application(i, e) → ((expand r) ⋅ (mark m) ⋅ t ⋅ (mark m)) e
...
Thursday, May 19, 2005
Freshness... with respect
In A New Approach to Abstract Syntax with Variable Binding, Pitts and Gabbay describe a "freshness" quantifier for their variant of set theory, where you can quantify over fresh names. This allows you to describe freshness conditions in a more formal way than the usual "x does not occur in M," and even reason about fresh names with formal logic. The quantification N x can be read: "for fresh x ..." This has a cool, dual universal/existential property: because the ambient universe of names is infinite, it's always true that there exists a fresh x, and because we don't care which one we choose, any proposition we prove using the freshness quantifier holds for all such fresh names.
What confused me for a while was that the quantifier just says "x is fresh;" it doesn't say "x is fresh with respect to M". But it seemed like if you take a name that's fresh at one point, but then use it in another context, you might have accidentally picked a name that conflicted with a name in the new context. In other words, I was concerned that having a local freshness condition without talking globally about all the names you're ever going to use doesn't carry enough information to avoid an incorrect choice of fresh name.
You have to dig a little deeper to see why this isn't a problem. The real meaning of the quantifier comes from the idea that the universe of names is infinite, but the construction of any particular term only involves a finite number of names. So not only can you find a fresh name at any point; but you can in fact choose any name other than the ones used in that term. So all but finitely many names are fresh. This is the more precise interpretation of N x: "for all but finitely many names x ..."
So the freshness quantifier isn't actually committing to a name. It's just saying that there's a huge set of names for which the proposition holds. Thus moving in and out of scope of particular terms doesn't affect the truth of a proposition built with the quantifier, because while the particular set of fresh names might change, the fact that that set involves all but a finite number of names does not. This allows us to abstract away from the actual choice of fresh names in a program when we're writing propositions about them.
What confused me for a while was that the quantifier just says "x is fresh;" it doesn't say "x is fresh with respect to M". But it seemed like if you take a name that's fresh at one point, but then use it in another context, you might have accidentally picked a name that conflicted with a name in the new context. In other words, I was concerned that having a local freshness condition without talking globally about all the names you're ever going to use doesn't carry enough information to avoid an incorrect choice of fresh name.
You have to dig a little deeper to see why this isn't a problem. The real meaning of the quantifier comes from the idea that the universe of names is infinite, but the construction of any particular term only involves a finite number of names. So not only can you find a fresh name at any point; but you can in fact choose any name other than the ones used in that term. So all but finitely many names are fresh. This is the more precise interpretation of N x: "for all but finitely many names x ..."
So the freshness quantifier isn't actually committing to a name. It's just saying that there's a huge set of names for which the proposition holds. Thus moving in and out of scope of particular terms doesn't affect the truth of a proposition built with the quantifier, because while the particular set of fresh names might change, the fact that that set involves all but a finite number of names does not. This allows us to abstract away from the actual choice of fresh names in a program when we're writing propositions about them.
Friday, May 13, 2005
The lambda machine
If the lambda calculus is a minimalist assembly language for modeling computation, then we can look at a lambda program as a mathematical black box with two possible outputs: halt and loop. These "outputs" of course correspond to whether a reduction in the abstract machine terminates, but we could just as well give them arbitrary labels, say, true and false.
When you encode a datatype and a computation in the lambda calculus, you might want to check that your computation gives the correct result, not just whether it halts. But the theorem will still be stated as a truth-valued proposition: either the computation got the right result, or it didn't. So assuming the encoding includes operations that can compare two results, you can always wrap the computation in an observer that drives the "lambda machine" to produce its true output (halt) if the computation produced the right result, and false output (loop forever) if the computation produced anything else.
For example, say we want to show that two different implementations of a function, f and f′, always produce the same result. We could do this directly by comparing their results, but this involves reasoning about the encoded result values. Since the datatype already has operations that simulate the inspection of its values, this would in a sense be a duplication of effort. Instead, we can use the observer operations--an equality test, for example--to compare the results to an expected value and then either halt or loop.
Thus if there is a context in which f and f′ are not equivalent, that is, in which they produce different results, then this implies that there is a context in which f causes the machine to halt and f′ causes the machine to loop. The statement of contextual equivalence is usually given as the contrapositive: if there are no such contexts, that is, in all contexts they either both halt or both loop (they "co-terminate"), then f and f′ are equivalent.
So these two outputs from the lambda machine are sufficient to formulate the statement of any proposition about expressions, so long as it depends only on properties that are observable within the lambda calculus.
When you encode a datatype and a computation in the lambda calculus, you might want to check that your computation gives the correct result, not just whether it halts. But the theorem will still be stated as a truth-valued proposition: either the computation got the right result, or it didn't. So assuming the encoding includes operations that can compare two results, you can always wrap the computation in an observer that drives the "lambda machine" to produce its true output (halt) if the computation produced the right result, and false output (loop forever) if the computation produced anything else.
For example, say we want to show that two different implementations of a function, f and f′, always produce the same result. We could do this directly by comparing their results, but this involves reasoning about the encoded result values. Since the datatype already has operations that simulate the inspection of its values, this would in a sense be a duplication of effort. Instead, we can use the observer operations--an equality test, for example--to compare the results to an expected value and then either halt or loop.
Thus if there is a context in which f and f′ are not equivalent, that is, in which they produce different results, then this implies that there is a context in which f causes the machine to halt and f′ causes the machine to loop. The statement of contextual equivalence is usually given as the contrapositive: if there are no such contexts, that is, in all contexts they either both halt or both loop (they "co-terminate"), then f and f′ are equivalent.
So these two outputs from the lambda machine are sufficient to formulate the statement of any proposition about expressions, so long as it depends only on properties that are observable within the lambda calculus.
How to read a semantics
Some tips for myself on how to read a semantics:
- Follow the textual description first. Usually they have thought about an order in which you should try to understand the rules.
- If you get stuck on one of the rules, circle the part that's confusing or write down what you don't get and skip it. Don't spend too long on any one part. (More often than not I embarrass myself by beating my head over something confusing only to find that it's explained in the next paragraph.)
- To understand the role a particular expression form plays, read its introduction and elimination rules. To understand the role an environment plays, read its extension and lookup rules. To understand any one of these rules, read its dual rule. Most of these rules make much more sense in pairs.
Tuesday, May 10, 2005
Lambda-encoding derivation, take 2
I had the basic idea of the lambda-encoding of lambda terms right, but I was sloppy with the type derivation. The important piece that I missed was that the result type of the continuation needs to appear in two places. In general, we say a type α is equivalently representable as a function from continuations to final results:
The derivation of disjoint unions as pure arrow types is simple, at least using the normal rules of classical logic:
Again, I'm not sure how hard this is to prove intuitionistically. But assuming that goes through okay, we get the type equivalence:
Or you can think of this in logical terms as the equivalenceα = (α → ο) → ο
I can prove this easily with classical logic, but I had trouble finding resources presenting the axioms and standard equivalences of intuitionistic logic, and I don't feel like trying to come up with a correct, intuitionistic derivation.α = (α ⇒ ο) ⇒ ο
The derivation of disjoint unions as pure arrow types is simple, at least using the normal rules of classical logic:
Notice how the currying makes much more sense than it did last time, now that the second occurrence of the result type is there. Implication and conjunction are obviously not equivalent (duh)! But you can curry a conjunction that occurs on the left-hand side of an implication.α ∨ β
= ((α ∨ β) ⇒ ο) ⇒ ο
= ((α ⇒ ο) ∧ (β ⇒ ο)) ⇒ ο
= (α ⇒ ο) ⇒ (β ⇒ ο) ⇒ ο
Again, I'm not sure how hard this is to prove intuitionistically. But assuming that goes through okay, we get the type equivalence:
α + β = (α → ο) → (β → ο) → ο
Saturday, May 07, 2005
Generative vs. generative
Crap. I just realized that I was borrowing a term to describe macros that already has another meaning in the macro literature. Generative macros, according to Ganz et al, are macros that do not inspect their arguments syntactically. I was using the term as I think it's used in the parameterized module literature, to mean procedures that produce different results every time they are invoked. Mumble.
Lambda-encoded lambda terms
In The Theory of Fexprs is Trivial, Mitch encodes a datatype in the lambda calculus that itself represents the abstract syntax of lambda calculus terms. The encoding trick involves both higher-order abstract syntax and some cute type equivalences.
Here's a data definition of the abstract syntax terms:
But we need to have some way of representing algebraic datatypes. For this we use the following equivalences:
Here's a data definition of the abstract syntax terms:
Notice that the variant representing abstractions is itself encoded using a (meta-language) abstraction. So we can represent the program λx.(x x) as:data Term α = Var α
| Abs (α → Term α)
| App (Term α) (Term α)
This is already a useful hack, because we don't have to come up with a datatype to represent variables, and if we wanted to deal with substitution it would be handled automatically by the substitution mechanisms of the meta-language.Abs (λx.(App (Var x) (Var x)))
But we need to have some way of representing algebraic datatypes. For this we use the following equivalences:
So to reduce the implementation of a k-variant disjoint union to pure lambda calculus, we CPS the values and split out their continuations into k separate partial continuations. Thus we get our final encoding of the abstract syntax of lambda terms:α + β → ο
≈ (α → ο) × (β → ο)
≈ (α → ο) → (β → ο)
Update: I hadn't made the⌈x⌉ = λabc.ax
⌈λx.M⌉ = λabc.b(λx.⌈M⌉)
⌈(M N)⌉ = λabc.c(⌈M⌉ ⌈N⌉)
Term datatype polymorphic in its variable type. I think this is right now.
Wednesday, April 27, 2005
If I were teaching macros
Yeah, if I were teaching macros I'd start without pattern matching. I would start with a programmed macro system like the one described by Dybvig et al, just without mentioning syntax-case. That way you'd have properly lexically scoped macros. And I wouldn't tell the students about datum->syntax-object so that they couldn't break hygiene. Here are some chapters in this hypothetical tutorial:
Lesson 1: Metaprogramming: programs that write programs.
Some might claim you can write macros in a hygienic macro system without understanding properly lexically scoped macros, since they're just taken care of for you. That's pretty much doomed to failure, because as a macro writer you need to understand the distinction between names and identifiers in order to know when you can and can't bind a particular identifier.
Lesson 1: Metaprogramming: programs that write programs.
Learn how to create syntax objects to create quoted code, by analogy to quote; talk about the phase distinction; write some simple macros that generate programs; make (over-)simplified analogy to cutting and pasting code.Lesson 2: Macros are embedded metaprograms.
Demonstrate that macros can refer to identifiers that are in scope. Show that there's no danger of such identifiers getting captured when macros are referentially transparent; refine the idea of cutting and pasting code to being more than just textual replacement -- a variable reference identifies a binding and the generated code reproduces that binding, not necessarily the name.Lesson 3: Macros can introduce identifiers.
Demonstrate how macros can introduce brand new identifiers; show that in hygienic macro systems those identifiers can never refer to existing bindings in any program, only to uses of the same identifier within a macro's templates; show how identifiers given as parameters can generate binding occurrences, bound occurrences, and quoted occurrences of the identifier.If I could get through all of that without pattern matching, that'd be cool, but somewhere along the line the code might just get too hairy without it. (Then again, Lisp defmacro hackers live without it, don't they?) Since pattern matching is orthogonal to the above lessons, I would love to put it off until after mastering metaprogramming, the phase separation, and issues of scope.
Some might claim you can write macros in a hygienic macro system without understanding properly lexically scoped macros, since they're just taken care of for you. That's pretty much doomed to failure, because as a macro writer you need to understand the distinction between names and identifiers in order to know when you can and can't bind a particular identifier.
Friday, April 22, 2005
When to reserve keywords
As I've pointed out before, when a macro uses literal keywords, the macro writer should reserve the keywords by binding them to macros that simply raise syntax errors if the keywords are used outside the context of invocations of the macro.
There are in fact two different ways that keywords get used in macros. The first we might describe as true syntactic sugar: in compound-unit/sig, there are always exactly three clauses, and their tags, import, link, and export, serve only to remind the reader of their purpose. Similarly, each (tag : signature) clause in the import clause only contains the : for readability. In this case, rebinding the keyword identifiers will just cause invocations of the macro to fail with a syntax error, because the use of the keyword at the invocation site doesn't have the same binding as the use of the keyword in the macro definition.
The second way that keywords get used, though, is as tags to distinguish different expression forms. In this case, if the keyword gets rebound, then a subexpression of the macro invocation will actually appear as a different kind of expression, which may very well succeed at matching some other case in the macro. The cond macro serves as an example:
There are in fact two different ways that keywords get used in macros. The first we might describe as true syntactic sugar: in compound-unit/sig, there are always exactly three clauses, and their tags, import, link, and export, serve only to remind the reader of their purpose. Similarly, each (tag : signature) clause in the import clause only contains the : for readability. In this case, rebinding the keyword identifiers will just cause invocations of the macro to fail with a syntax error, because the use of the keyword at the invocation site doesn't have the same binding as the use of the keyword in the macro definition.
The second way that keywords get used, though, is as tags to distinguish different expression forms. In this case, if the keyword gets rebound, then a subexpression of the macro invocation will actually appear as a different kind of expression, which may very well succeed at matching some other case in the macro. The cond macro serves as an example:
This macro essentially declares the "question" subexpression of each clause to have a kind of union type: a question is either an expression or the keyword else. If, at the macro invocation site, the identifier else isn't bound the same way as it was in the macro definition, it is still an expression, so it matches the second case of the macro:(define-syntax cond
(syntax-rules (else)
[(_ [else a-exp]) a-exp]
[(_ [q0-exp a0-exp] [q1-exp a1-exp] ...)
(if q0-exp a0-exp (cond [q1-exp a1-exp] ...))]))
It's in this second case that reserving keywords is really important. In the first case, you get an error, but you find out right away and can fix it. In the second, you may not get an error at all, or the error may not appear until much later in the program.(let ([else #f])
(cond
[else 23]))
; => #<void>
Ask and ye shall receive my bugs
Naturally, the macro I posted yesterday is broken. (It was only a matter of time, right?) Sadly, not only did I have to rely on Ryan to fix it for me, but I don't even quite understand the fix. In fact, he doesn't even totally understand why the fix worked. Bleah.
Let's consider a hypothetical example to understand the problem better. The user invents a new language called my-lang with keywords foo and mumble, and a variant of syntax-case called my-syntax-case. The problem has to do with the fact that the definition of the my-syntax-case macro introduces foo and mumble into its output (because invocations of my-syntax-case don't have to mention the keywords). So they get fresh marks, which distinguish them from the original foo and mumble. The solution is to cancel the fresh marks with syntax-local-introduce.
I won't reproduce the entire corrected macro, but here's the relevant portion of the second of the two cases (the simpler one, where there is no parent language):
Let's consider a hypothetical example to understand the problem better. The user invents a new language called my-lang with keywords foo and mumble, and a variant of syntax-case called my-syntax-case. The problem has to do with the fact that the definition of the my-syntax-case macro introduces foo and mumble into its output (because invocations of my-syntax-case don't have to mention the keywords). So they get fresh marks, which distinguish them from the original foo and mumble. The solution is to cancel the fresh marks with syntax-local-introduce.
I won't reproduce the entire corrected macro, but here's the relevant portion of the second of the two cases (the simpler one, where there is no parent language):
Also, I should point out that it wasn't necessary to require at least one clause in the syntax-case variant, so I've corrected that, too.————
;; define the new language-specific syntax-case variant
(define-syntax (case stx)
(syntax-case stx ()
[(_ stx-exp (extra-kw (... ...)) clause (... ...))
(with-syntax ([(k (... ...))
(map syntax-local-introduce
(syntax->list #'(kw ...)))])
(syntax-case stx-exp (k (... ...) extra-kw (... ...))
clause (... ...)))]))
————
Hygienic macros are generative
In normal functional programming, we can "substitute equals for equals" -- any two equivalent expressions are interchangeable, because they will always produce equivalent results. This allows for all sorts of refactoring, because you can pull out an expression from one lexical context, stick it in another context, and expect it to behave the same.
Any functional programmer who's been burned by programmed macros such as syntax-case will tell you that when they try to refactor their macros in simple ways -- in particular, separating out pieces of a complicated macro and moving them into helper functions -- the macros suddenly stop working!
This is because in a hygienic macro system, syntax transformers are not pure functions. The hygiene condition requires that, in order to avoid unwanted capture, every use of a syntax transformer must generate different binding occurrences of identifiers! This is analogous to applicativity vs. generativity in ML-style parameterized module systems: applicative functions generate the same output for the same input, whereas generative functions are guaranteed to have different results every time you invoke them.
In a sense, this reminds me of the balance between expressive power vs. local reasoning, because hygiene introduces a non-local effect that ruins the ability to understand a macro in isolation. (Happily, there are limitations on these effects; for example, the "freshness monad" is known to be commutative, meaning that it doesn't matter what order you generate fresh names in, because they're all distinct anyway.) I wonder what kind of reasoning tools can help mitigate the problems hygiene causes with understanding macros.
Any functional programmer who's been burned by programmed macros such as syntax-case will tell you that when they try to refactor their macros in simple ways -- in particular, separating out pieces of a complicated macro and moving them into helper functions -- the macros suddenly stop working!
This is because in a hygienic macro system, syntax transformers are not pure functions. The hygiene condition requires that, in order to avoid unwanted capture, every use of a syntax transformer must generate different binding occurrences of identifiers! This is analogous to applicativity vs. generativity in ML-style parameterized module systems: applicative functions generate the same output for the same input, whereas generative functions are guaranteed to have different results every time you invoke them.
In a sense, this reminds me of the balance between expressive power vs. local reasoning, because hygiene introduces a non-local effect that ruins the ability to understand a macro in isolation. (Happily, there are limitations on these effects; for example, the "freshness monad" is known to be commutative, meaning that it doesn't matter what order you generate fresh names in, because they're all distinct anyway.) I wonder what kind of reasoning tools can help mitigate the problems hygiene causes with understanding macros.
Thursday, April 21, 2005
You asked for it, Felix
Well, I'm not sure if you can quite call it a macro-defining-macro-defining macro, but it's still meta enough to be entertaining. Here's the rough idea. I found I wanted to use a lot of macro keywords when defining an embedded language: the various constructors of the terms of the language are keywords recognized by the macro, which get compiled down to core Scheme. It turned out my compilation would best proceed in a couple of passes, so I borrowed an idea from Sarkar et al's paper at last year's ICFP: I have a define-lang macro that can define either a stand-alone embedded language or an extension to an existing embedded language. The define-lang macro produces:
- a static registry of the keywords associated with the language as well as a link to its parent language
- a specialized version of syntax-case tailored to the new language -- essentially a wrapper around syntax-case that automatically adds the language's keywords to the literals list
And this declaration will generate a new calc-syntax-case macro, which can be used to define macros on the calc-lang language:(define-lang calc-lang calc-syntax-case (<+> <-> <*> </>))
Notice that I didn't have to add the keywords to the literals list of calc-syntax-case, because it adds them already. (I left in the literals list argument to calc-syntax-case in case I need to add more keywords to a particular macro.) Now let's say I want to add an exponentiation operation to the calc-lang, which compiles down to the core calc-lang language. Then we would add the new operation with(define-syntax (compile-calc-program stx)
(calc-syntax-case stx ()
[(<+> e1 e2) ————]
[(<-> e1 e2) ————]
[(<*> e1 e2) ————]
[(</> e1 e2) ————]))
So here's the approximate definition of define-lang:(define-lang (extended-calc-lang calc-lang) extended-calc-syntax-case (<pow>))
Incidentally, notice that since these macros produce a whole lots of keywords, it's important to do something to reserve the keywords to get decent module-level scoping behavior.(define-for-syntax (lang-keywords lang-name)
———— recursively collect all keywords from static registry ————)
(define-syntax (define-lang stx)
(syntax-case stx ()
[(_ (lang-name parent-name) case (kw ...))
(with-syntax ([(parent-kw ...) (lang-keywords #'parent-name)])
#'(begin
;; register the static information about the language
(define-syntax lang-name
(list #'parent-name
(list #'kw ...)))
;; define the language-specific syntax-case variant
(define-syntax case
(syntax-rules ()
[(_ stx-exp (extra-kw (... ...))
clause1 clause2 (... ...))
(syntax-case stx-exp
(parent-kw ... kw ... extra-kw (... ...))
clause1 clause2 (... ...))]))))]
[(_ lang-name case (kw ...))
#'(begin
;; register the static information about the language
(define-syntax lang-name
(list #f (list #'kw ...)))
;; define the new language-specific syntax-case variant
(define-syntax case
(syntax-rules ()
[(_ stx-exp (extra-kw (... ...))
clause1 clause2 (... ...))
(syntax-case stx-exp (kw ... extra-kw (... ...))
clause1 clause2 (... ...))])))]))
Wednesday, April 20, 2005
Saturday, April 16, 2005
Good hackers work with what they've got
[File under squishy musings... -Ed.]
From Gian-Carlo Rota's Ten Lessons I Wish I Had Been Taught:
It's a constant source of heartburn to computer scientists that, for example, the space of viable algorithms (say, the ones that run in polynomial time) is one tiny speck in the universe of algorithms we wish we could use. And lots of folks from Dijkstra to AOP advocates have tried vainly to abstract out efficiency as a separate concern. While we're at it, let's imagine some extreme violations of reality -- let's say I want to create a computer program that does my research for me, grows wings, and cooks me dinner in response to picking up on my brain wave patterns that indicate my desire for it to do so, but never mind the details of how it works.
I suppose this means that ultimately someone has to be responsible for the details. Maybe that's the key: you can only set up a reasonable interface to hide an implementation if the implementation can truly deliver on its contract with the client. Which means that deciding on the interface to begin with relies on a balance between hiding enough from the client on the one hand but being plausible for the provider to achieve on the other. Feynman suggests one way to go about solving this: set ridiculously high goals for yourself, rely on being a genius, and be on the constant lookout for possible solutions.
But I was also struck by Joel Webber's description of the technology behind Google Maps. In particular, when I read about their use of PNG alpha-channels to implement drop-shadows for the pushpins that get overlaid on a map, it occurred to me that this is an absolutely unnecessary feature, and yet an incredibly nice touch. Clearly there wasn't some suit at Google demanding, "dammit, drop shadows are a deal breaker. Get me drop shadows!" Rather, I imagine someone thought, hey, if we stick a semi-transparent PNG on top of an image we can get a nice shadow effect. I bet that would make us look cooler than Apple!
Maybe good hackers work from the bottom up, starting with their existing bag of tricks and figuring out what they can solve with them. Or maybe they work like Feynman, always on the lookout for solutions to the Big Problems. Chances are, good hackers work with what they've got, be it a tool set or a problem set.
From Gian-Carlo Rota's Ten Lessons I Wish I Had Been Taught:
Richard Feynman was fond of giving the following advice on how to be a genius. You have to keep a dozen of your favorite problems constantly present in your mind, although by and large they will lay in a dormant state. Every time you hear or read a new trick or a new result, test it against each of your twelve problems to see whether it helps. Every once in a while there will be a hit, and people will say: "How did he do it? He must be a genius!"I was thinking about database abstractions and how often people get in pissing matches over whether it's even possible or desirable to abstract over persistence. In teaching abstraction, we advocate information hiding as a way of building scalable software, but then there's always some detractor who can't wait to snipe at you just for trying: "no, you can't hide that detail, that's simply too prevalent an issue." Sometimes history proves them wrong, sometimes not.
It's a constant source of heartburn to computer scientists that, for example, the space of viable algorithms (say, the ones that run in polynomial time) is one tiny speck in the universe of algorithms we wish we could use. And lots of folks from Dijkstra to AOP advocates have tried vainly to abstract out efficiency as a separate concern. While we're at it, let's imagine some extreme violations of reality -- let's say I want to create a computer program that does my research for me, grows wings, and cooks me dinner in response to picking up on my brain wave patterns that indicate my desire for it to do so, but never mind the details of how it works.
I suppose this means that ultimately someone has to be responsible for the details. Maybe that's the key: you can only set up a reasonable interface to hide an implementation if the implementation can truly deliver on its contract with the client. Which means that deciding on the interface to begin with relies on a balance between hiding enough from the client on the one hand but being plausible for the provider to achieve on the other. Feynman suggests one way to go about solving this: set ridiculously high goals for yourself, rely on being a genius, and be on the constant lookout for possible solutions.
But I was also struck by Joel Webber's description of the technology behind Google Maps. In particular, when I read about their use of PNG alpha-channels to implement drop-shadows for the pushpins that get overlaid on a map, it occurred to me that this is an absolutely unnecessary feature, and yet an incredibly nice touch. Clearly there wasn't some suit at Google demanding, "dammit, drop shadows are a deal breaker. Get me drop shadows!" Rather, I imagine someone thought, hey, if we stick a semi-transparent PNG on top of an image we can get a nice shadow effect. I bet that would make us look cooler than Apple!
Maybe good hackers work from the bottom up, starting with their existing bag of tricks and figuring out what they can solve with them. Or maybe they work like Feynman, always on the lookout for solutions to the Big Problems. Chances are, good hackers work with what they've got, be it a tool set or a problem set.
Friday, April 15, 2005
The balance of expressiveness and reasonability
Yesterday during the question and answer period of a talk, Matthias pointed out that there is usually a balance involved in language design between the expressive power of the language and the ability to do local reasoning on programs in the language. This confirmed and crystallized an intuition I've been mulling for a while. It was always clear to me that an increase in expressivity is not inherently "good" (for example, in his expressivity paper, Matthias proves that set! increases the expressive power of a language, but he certainly wasn't advocating the gratuitous use of mutation). But I hadn't quite put my finger on it until Matthias's comment.
It's in fact a direct result of the idea that powerful language constructs require global transformations: when you use a construct that affects your whole program, then you have to reason globally about the changes it makes. Essentially this means you'll need more powerful reasoning tools to be able to tame the power -- which can be both constructive and destructive -- of the new language feature.
As a simple example, the other day I was writing some pattern matching code in "substitution-passing style," where the matcher returns either a substitution or #f, the latter indicating that it failed to match. But before I knew it, I ended up with loads of intermediate checks to see if intermediate matches had failed. The real kicker was when I started writing helper functions (match-list) that themselves had to propagate these checks. I finally decided that there was no need to reimplement a poor man's exception mechanism when my implementation language already has one. So I changed the interface to have matchers raise a match-error exception when matching fails. But the upshot is that the code no longer locally indicates that such an exception can occur; this property then ends up in comments and in proof obligations of the clients.
Type and effect systems like Java's checked exceptions can mitigate these non-local changes by checking and maintaining invariants about the effects. This is precisely an example of the kinds of reasoning tools that help tame the power of expressive language features.
Another example is dynamic dispatch in OO languages. I was having a discussion last year with Shriram about local reasoning and AOP, and he made an analogy to dynamic dispatch. Programmers are completely accustomed to looking at a local piece of code and not knowing its behavior, he argued; in OO languages a method call could refer to any arbitrary reimplementation of the method. But this is par for the course, and in practice we assume that the reimplementations will be well-behaved.
Furthermore, we don't use this power with reckless abandon. I found a relevant quote from an aside made by Paul Wilson in the midst of an unrelated Usenet conversation:
I believe that the core principles of program design (should) stem from functional programming. But many important design principles require more powerful tools than pure functional programming offers. So more powerful language features are important. On the other hand, any time you introduce effects that can affect the behavior of arbitrary parts of a program, you need to be able to mitigate those changes with reasoning tools, whether they are proof techniques or automated reasoning software.
1As Moore's law allows lightweight formal methods to get closer to what used to be heavyweight formal methods, we should be able to make more powerful reasoning tools for our programs, which should allow us to slide the scale further in favor of more expressive language features. Which is all to say that I should really check out Shriram and Kathi's work on formal methods for AOP.
It's in fact a direct result of the idea that powerful language constructs require global transformations: when you use a construct that affects your whole program, then you have to reason globally about the changes it makes. Essentially this means you'll need more powerful reasoning tools to be able to tame the power -- which can be both constructive and destructive -- of the new language feature.
As a simple example, the other day I was writing some pattern matching code in "substitution-passing style," where the matcher returns either a substitution or #f, the latter indicating that it failed to match. But before I knew it, I ended up with loads of intermediate checks to see if intermediate matches had failed. The real kicker was when I started writing helper functions (match-list) that themselves had to propagate these checks. I finally decided that there was no need to reimplement a poor man's exception mechanism when my implementation language already has one. So I changed the interface to have matchers raise a match-error exception when matching fails. But the upshot is that the code no longer locally indicates that such an exception can occur; this property then ends up in comments and in proof obligations of the clients.
Type and effect systems like Java's checked exceptions can mitigate these non-local changes by checking and maintaining invariants about the effects. This is precisely an example of the kinds of reasoning tools that help tame the power of expressive language features.
Another example is dynamic dispatch in OO languages. I was having a discussion last year with Shriram about local reasoning and AOP, and he made an analogy to dynamic dispatch. Programmers are completely accustomed to looking at a local piece of code and not knowing its behavior, he argued; in OO languages a method call could refer to any arbitrary reimplementation of the method. But this is par for the course, and in practice we assume that the reimplementations will be well-behaved.
Furthermore, we don't use this power with reckless abandon. I found a relevant quote from an aside made by Paul Wilson in the midst of an unrelated Usenet conversation:
It turns out that at most overtly polymorphic call sites in OO programs, the receiver is always of the same class. And of the minority of truly polymorphic call sites, there's only two or three classes of receiver. That makes it sound like OO doesn't do much work for you. But it does, really, because the 10% of sites where you need it, you need it bad.Now, I was initially unhappy with these "pragmatic" justifications of language features that destroy local reasoning. They seemed to pit abstraction and local reasoning on one side against usefulness and practicality on the other, and I'm simply not prepared to give up on abstraction. I just don't see how anyone could survive a software project without it. But the underlying tension is this one between expressive power and local reasoning. So good language design requires a sweet spot between features that are just powerful enough to express the kinds of things you want to express while not being too much harder to reason about.1
I believe that the core principles of program design (should) stem from functional programming. But many important design principles require more powerful tools than pure functional programming offers. So more powerful language features are important. On the other hand, any time you introduce effects that can affect the behavior of arbitrary parts of a program, you need to be able to mitigate those changes with reasoning tools, whether they are proof techniques or automated reasoning software.
1As Moore's law allows lightweight formal methods to get closer to what used to be heavyweight formal methods, we should be able to make more powerful reasoning tools for our programs, which should allow us to slide the scale further in favor of more expressive language features. Which is all to say that I should really check out Shriram and Kathi's work on formal methods for AOP.
Monday, April 11, 2005
Reader macros
PLT has reader macros!
When I get around to it, I'd like to create a read syntax where you can annotate procedure definitions with documentation, and a Javadoc-like tool can easily extract the information. Semantically meaningful comments make my teeth itch, and in a language where Code Is Data™, code documentation ought to be something that can be extracted without having to write a custom parser.
When I get around to it, I'd like to create a read syntax where you can annotate procedure definitions with documentation, and a Javadoc-like tool can easily extract the information. Semantically meaningful comments make my teeth itch, and in a language where Code Is Data™, code documentation ought to be something that can be extracted without having to write a custom parser.
Monday, April 04, 2005
Accumulators
When I took COMP210 from Matthias as a freshman at Rice, I didn't understand why he even bothered pointing out the notion of an accumulator, or why it had such a fancy name. If you need to give more information to another procedure you give it an extra argument -- duh. Why all the commotion?
There are many reasons why accumulators are so fundamental. First of all, accumulator-passing style--a "style" is what the FP cool kids call a design pattern--is a functional way to simulate mutation. It's used in semantics and it's used in functional programs to preserve referential transparency. The one-sentence justification for functional update is that it renders the dependencies of the function explicit, which makes the function's invariants clearer, and generally has the effect that you can't cheat and mistakenly call the procedure in an invalid state.
Once you become comfortable with accumulator-passing style, you start being able to write iterative loops that are more general and natural than for or while loops, and avoid nasty dependencies on statement order that arise from imperative update. This is one of those things that just drive you crazy after a while in C. What's really nice about the "named let" construct in Scheme is that you can easily write tail-recursive procedures that can be compiled to loops, which you can essentially think of as "while with arguments."
The next step, once you've mastered accumulator-passing style and named let, is to understand fold. I know, it makes Guido's head hurt. But never mind the haters. Accumulators are a general pattern of building up a result by successive approximations. And a subset of this pattern is when the construction of the result is driven by the deconstruction of an input, particularly a list. It happens that a whole bunch of the time, we build up some result by adding to it the result of computing something for every item in a list. For example, imagine a Scheme interpreter that adds a bunch of variable bindings to an environment: it starts with an initial environment, and one at a time it goes through the list of new bindings, each time generating a new environment with the added binding.
And here's the kicker--just for fun, once you've become a master of functional folds, you are primed to understand fixed-point constructions. The very idea of successive approximations to a result is the key to a fixed-point algorithm; the difference is what drives the recursion. In a fold, it's the simple deconstruction of a list that determines when to stop, whereas in a fixed-point recursion, it's when the approximations stop changing the result that the algorithm terminates.
Finally, once you can write fixed-point algorithms while standing on your head and whistling Jerusalem, you're ready to understand the Y combinator. Remember how when you first learned to write recursive functions, you had to teach yourself not to try to imagine the entire nested computation, but just to trust the recursive call to do its job? Well, you'll never be able to imagine an infinite fixed-point construction, so here this mental laziness is crucial.
When you understand what successive approximation has to do with all of these concepts, you will have achieved enlightenment.
There are many reasons why accumulators are so fundamental. First of all, accumulator-passing style--a "style" is what the FP cool kids call a design pattern--is a functional way to simulate mutation. It's used in semantics and it's used in functional programs to preserve referential transparency. The one-sentence justification for functional update is that it renders the dependencies of the function explicit, which makes the function's invariants clearer, and generally has the effect that you can't cheat and mistakenly call the procedure in an invalid state.
Once you become comfortable with accumulator-passing style, you start being able to write iterative loops that are more general and natural than for or while loops, and avoid nasty dependencies on statement order that arise from imperative update. This is one of those things that just drive you crazy after a while in C. What's really nice about the "named let" construct in Scheme is that you can easily write tail-recursive procedures that can be compiled to loops, which you can essentially think of as "while with arguments."
The next step, once you've mastered accumulator-passing style and named let, is to understand fold. I know, it makes Guido's head hurt. But never mind the haters. Accumulators are a general pattern of building up a result by successive approximations. And a subset of this pattern is when the construction of the result is driven by the deconstruction of an input, particularly a list. It happens that a whole bunch of the time, we build up some result by adding to it the result of computing something for every item in a list. For example, imagine a Scheme interpreter that adds a bunch of variable bindings to an environment: it starts with an initial environment, and one at a time it goes through the list of new bindings, each time generating a new environment with the added binding.
And here's the kicker--just for fun, once you've become a master of functional folds, you are primed to understand fixed-point constructions. The very idea of successive approximations to a result is the key to a fixed-point algorithm; the difference is what drives the recursion. In a fold, it's the simple deconstruction of a list that determines when to stop, whereas in a fixed-point recursion, it's when the approximations stop changing the result that the algorithm terminates.
Finally, once you can write fixed-point algorithms while standing on your head and whistling Jerusalem, you're ready to understand the Y combinator. Remember how when you first learned to write recursive functions, you had to teach yourself not to try to imagine the entire nested computation, but just to trust the recursive call to do its job? Well, you'll never be able to imagine an infinite fixed-point construction, so here this mental laziness is crucial.
When you understand what successive approximation has to do with all of these concepts, you will have achieved enlightenment.
Sunday, April 03, 2005
What contexts represent
One of my pet peeves is that people always pay lip service to explaining what contexts are, and they always end up saying the same thing, which means absolutely nothing to people who don't already know what contexts are. They always say, "a context is an expression with a hole." This is basically a useless introduction. If you expect your audience to know what a context is, don't waste their time re-explaining it. If you don't expect them to know, then for God's sake, give them a real explanation.
The notion of a program context can be used to describe a number of ideas. So you could approach it from a number of angles.
Although I found the phrase "an expression with a hole" opaque as a first year grad student, I do like the metaphor of a hole. But it's important to motivate it with an application. For PL students learning about semantics, it's probably useful to take the compatible closure angle. Otherwise, observational equivalence is probably the most accessible approach.
The notion of a program context can be used to describe a number of ideas. So you could approach it from a number of angles.
- Compatible closure - the β-reduction rule isn't useful until you extend it to operate within the context of a whole program.
- Observational equivalence - even non-PL programmers are familiar with the idea of "substituting equals for equals" -- Liskov made the substitution principle famous to OO programmers, for example. So you can talk about being able to place two different expressions into the same context and observing the results.
- Quasiquotation - a quasiquoted code template constructs a term with holes in it where you can splice in code.
- Macros - similarly, the template in a syntax-rules macro, for example, is an expression context with named holes for all the pattern variables.
- Evaluation order - this goes along with the idea of compatible closure; since understanding how β-reduction applies within the context of a whole program requires knowing how to find the next expression to reduce, the grammar of evaluation contexts is a specification for the algorithm that finds the redex.
Although I found the phrase "an expression with a hole" opaque as a first year grad student, I do like the metaphor of a hole. But it's important to motivate it with an application. For PL students learning about semantics, it's probably useful to take the compatible closure angle. Otherwise, observational equivalence is probably the most accessible approach.
Saturday, April 02, 2005
Three ways to label expressions
Static analyses like CFA compute results for each subexpression of a program. Consequently the result of such an analysis is a map from individual subexpressions to answers. But consider the following program:
Since a program may contain identical subexpressions, there needs to be some way to distinguish seemingly identical terms. But the program already contains enough information to distinguish all subexpressions: their distinction is precisely the program context in which they occur. So one way to label subexpressions is to make the result of the analysis a map from program contexts to results:((lambda (x) x) (lambda (x) x))
Context → ValBut comparison of two expressions by recursively comparing their entire program context is inefficient. We can optimize this by representing each position in the program as a unique label, and then implement these labels with a datatype that has a fast comparison operation (such as integers or symbols):
Label → ValBut there's another possible representation hack. Sometimes we happen to be working with a language whose expressions themselves contain information that distinguishes them from all other expressions. A program in A-normal form binds every subexpression to a local variable. If we make sure that each such variable has a unique name*, then our analysis can simply map the variable of each let-expression to a result:
Var → Val*As they point out on p.142 of Principles of Program Analysis, there's not actually a requirement that the labels be unique, but an analysis that identifies two distinct expressions will potentially be less precise.
Subscribe to:
Posts (Atom)

