Sunday, December 19, 2010

how about a pattern-matching version of "let loop"?

I tend to use the "named let" idiom a lot, to me it's the most general form of looping construct, and is more readable than artificial constructs like 'do'.

I've begun to pine for a pattern-matching version of that construct, though. Not sure how well it would fly, but it would nicely generalize pattern matching. The reason I like 'named let' is because it lets you compactly introduce a recursive function while keeping the initial arguments in a place that makes the whole construct easier to understand.

Here's what the 'length' function looks like right now:

(define (length l)
  (define fun
    acc ()        -> acc
    acc (hd . tl) -> (fun (+ 1 acc) tl)
  (fun 0 l)))

And here's what it might look like with a pattern-matching 'named let' variant:

(define (length l)
  (let loop (0 l)
    acc ()        -> acc
    acc (hd . tl) -> (loop (+ 1 acc) tl)))

Visually I think it should be easy to distinguish from a normal let by the lack of extra levels of parens in the 'binding' spot... and this is in addition to the obvious -> symbols.

One bad side-effect of this is that let could no longer be done with defmacro (as in lib/derived.scm), and would require a special hack in the parser...

1 comment:

  1. Oooh, here's another possible syntax, this might be even better:

    (let (loop 0 1)