Search code examples
schememacrosnesteddefine-syntax

Scheme Macro for nesting expressions


Can a macro be written in Scheme (with define-syntax, for example) which will take expressions like this:

(op a b c d e f g h i j)

And yield expressions like this as output?

(op (op (op (op (op (op (op (op (op a b) c) d) e) f) g) h) i) j) 

Of course, for arbitrary lengths. I can't think of a way to do it, given some template like this:

(define-syntax op
  (syntax-rules ()
    [(_) 'base-case]
    [(v1 v2 ...) 'nested-case??]))

Solution

  • (define bop list)
    
    (define-syntax op
      (syntax-rules ()
        ((op a b) (bop a b))
        ((op a b c ...) (op (bop a b) c ...))))
    

    For example, (op 1 2 3 4) expands to (bop (bop (bop 1 2) 3) 4) and evaluates to (((1 2) 3) 4).