Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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??]))
like image 775
Claudiu Avatar asked Dec 04 '08 10:12

Claudiu


2 Answers

(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).

like image 82
namin Avatar answered Nov 15 '22 07:11

namin


The function you want to apply to the arguments should itself be an argument to the macro. Barring that, my solution was the same.

#!r6rs

(import (rnrs base))

(define-syntax claudiu
  (syntax-rules ()
    ((claudiu fun first second)
     (fun first second))
    ((claudiu fun first second rest ...)
     (claudiu fun (claudiu fun first second) rest ...))))
like image 33
grettke Avatar answered Nov 15 '22 07:11

grettke