gpt4 book ai didi

macros - cadr、caddr 等的可变版本

转载 作者:行者123 更新时间:2023-12-02 23:49:40 25 4
gpt4 key购买 nike

我想知道如何在 Racket 中实现 cadr、caddr 等的可变版本,而不需要单独定义每个版本? IE。不

(define (mcadr exp)
(mcar (mcdr exp)))

对于可变列表或对,Racket 似乎仅支持 mcar 和 mcdr,但不支持“扩展”版本。我需要了解并擅长宏才能做到这一点吗?

最佳答案

这是一个宏解决方案:

#lang racket/base

(require racket/mpair (for-syntax racket/base))

(define-syntax (define-combinations stx)
(syntax-case stx ()
[(_ n) (integer? (syntax-e #'n))
(let ([n (syntax-e #'n)])
(define options (list (cons "a" #'mcar) (cons "d" #'mcdr)))
(define (add-options r)
(apply append
(map (λ (opt)
(map (λ (l) (cons (string-append (car opt) (car l))
(list (cdr opt) (cdr l))))
r))
options)))
(define combinations
(cdddr
(let loop ([n n] [r '(("" . x))])
(if (zero? n) r (append r (loop (sub1 n) (add-options r)))))))
(define (make-name combo)
(let ([s (string->symbol (string-append "mc" (car combo) "r"))])
(datum->syntax stx s stx)))
(with-syntax ([(body ...) (map cdr combinations)]
[(name ...) (map make-name combinations)])
#'(begin (define (name x) body) ...)))]))

(define-combinations 4)
(mcaddr (mlist 1 2 3 4 5))

关于macros - cadr、caddr 等的可变版本,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6240033/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com