本文介绍了嵌套表达式的方案宏的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

是否可以在Scheme中编写宏(例如,使用define-syntax),该宏将采用以下表达式:

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??]))

推荐答案

(define bop list)

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

例如,(op 1 2 3 4)扩展为(bop (bop (bop 1 2) 3) 4)并计算为(((1 2) 3) 4).

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

这篇关于嵌套表达式的方案宏的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-23 20:02