07 December 2009

Prefix notation via closures

For the programmers in the audience...

Recently I’d read yet again someone saying that prefix notation is one of the things keeping more people from using Lisp. As I’ve said before, I find it hard to believe that this is an obstacle in practice. Especially since so many languages limit infix notation to essentially numbers (and only built-in numeric types at that) and Boolean values.

(Keep in mind that I’m saying this as someone who was raised on C rather than Lisp.)

Then I started thinking about the way that method invocation in many object-oriented languages is infixish. Consider Smalltalk: "hello" at: 3 Or Java: "hello".charAt(3) Or even: bigInt.add(anotherBigInt)

So, by using the closure-as-object idiom in Scheme...

(define (number-object-ctor n)
(λ (op arg)
  (if op
      (number-object-ctor (op n (arg #f #f)))

(define (print-number-object n)
(display (n #f #f))

(define x (number-object-ctor 4))
(define y (number-object-ctor 5))

(print-number-object (x + y))
(print-number-object ((x * x) + (y * y)))

It’s not as practical as an infix macro. I just thought it was interesting, however, that prefix notation could be twisted into infix notation that way.

No comments: