Scheme Macro for nesting expressions
Asked Answered
F

3

5

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??]))
Franzen answered 4/12, 2008 at 10:50 Comment(2)
I am curious. Was this just a question of theoretical interest or do you have an interesting use case? In general, that kind of wrapping would be achieved by a foldLeft.Casablanca
hmm, good point. i mostly asked this because i didn't think of your way =P. i didn't realize this is exactly what foldl does.Franzen
C
6
(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).

Casablanca answered 4/12, 2008 at 11:40 Comment(2)
Why are you using bop in the literal identifiers if you are not matching it?Boeotia
scheme macros are really really smart with their ... aren't they?Franzen
G
1

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 ...))))
Gallic answered 10/12, 2008 at 20:27 Comment(0)
F
0

To show how the answer works out:

(op 1 2 3 4)

This is an op with 4 statements, so the 2nd case gets selected with a=1, b=2, c=3, ...=4:

(op (bop 1 2) 3 4)

This is an op with 3 statements, so 2nd case again. a=(bop 1 2), b=3, c=4:

(op (bop (bop 1 2) 3) 4)

Now this is a bop with 2 statements, so a=(bop (bop 1 2) 3), b=4, and it's done.

Franzen answered 4/12, 2008 at 18:52 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.