• re: Elegant solution asked

    From B. Pym@Nobody447095@here-nor-there.org to comp.lang.lisp on Sat Aug 30 08:30:57 2025
    From Newsgroup: comp.lang.lisp

    Barry Margolin wrote:

    (defun map-with-constant (mapping-function function constant &rest lists)
    (apply mapping-function function (circular-list constant) lists))

    This can then be used as
    (map-with-constant #'mapcar #'cons 1 '(1 2 3)) =>
    ((1 . 1) (1 . 2) (1 . 3)).


    Scheme

    (% map (cons 'X _) '(1 2 3))
    ===>
    ((X . 1) (X . 2) (X . 3))

    Given:


    ;; Anaphoric macro to abbreviate lambdas for higher-order functions.
    ;; Uses "_" for 1 argument;
    ;; uses "A:" and "B:" and so on for 2 or more arguments.
    ;; This version works under both Gauche Scheme
    ;; and Racket. Racket needs:
    ;; (require compatibility/defmacro)
    ;; When used with functions such as "map" and "fold", the macro
    ;; can deduce the number of arguments the lambda will receive.
    ;; The number of arguments can be specified by an integer
    ;; after the function name. For example:
    ;; (% 2 lset-adjoin (eq? B: (char-upcase A:)) '(#\M #\N) #\m #\o)
    ;;
    (define-macro %
    (case-lambda
    ((func expr List) `(,func (lambda(_) ,expr) ,List))
    ((func expr . more)
    ;; Number of arguments received by the lambda.
    (let ((n (if (integer? func)
    (begin0
    func
    (set! func expr)
    (set! expr (car more))
    (set! more (cdr more)))
    (length more))))
    (let* ((nums (do ((i n (- i 1))
    (r '() (cons (+ i 64) r))) ((= 0 i) r)))
    (vnames
    (map (lambda(n)
    (string->symbol (string (integer->char n) #\:)))
    nums)))
    `(,func (lambda ,vnames ,expr) ,@more))))))
    --- Synchronet 3.21a-Linux NewsLink 1.2