Sujet : Re: Emacs Lisp's "mapconcat" in Common Lisp?
De : Nobody447095 (at) *nospam* here-nor-there.org (B. Pym)
Groupes : comp.lang.lisp comp.lang.schemeDate : 31. Aug 2024, 01:21:11
Autres entêtes
Organisation : A noiseless patient Spider
Message-ID : <vatk56$md9s$1@dont-email.me>
User-Agent : XanaNews/1.18.1.6
Pascal Bourguignon wrote:
Teemu Likonen <tlikonen@iki.fi> writes:
It's a Common Lisp newbie here; I'm more experienced in Emacs Lisp. I
wonder if there is similar function in CL like Emacs Lisp's "mapconcat":
>
(mapconcat 'identity '("one" "two" "three") "-")
=> "one-two-three"
>
I can do the same in CL with this:
>
(let ((list '("one" "two" "three")))
(format nil "~{~a-~}~a" (butlast list) (car (last list))))
>
But I have a feeling that there could be a more elegant way. Is there?
Yes, write: (mapconcat 'identity '("one" "two" "three") "-") ; elegant!
Of course, with:
(defun mapconcat (fun list sep)
(when list
(let ((~sep (with-output-to-string (*standard-output*)
(map nil (lambda (ch) (princ (if (char= #\~ ch) "~~" ch)))
sep))))
(format nil (format nil "~~A~~{~A~~A~~}" ~sep)
(funcall fun (first list))
(mapcar fun (rest list))))))
(mapconcat 'identity '("one" "two" "three") "-")
--> "one-two-three"
(mapconcat (lambda (x) (concatenate 'string "[" x "]")) '("one" "two" "three") "
~")
--> "[one]~[two]~[three]"
Gauche Scheme:
(define (mapconcat fun lst sep)
(reduce-right
(^(a b)
(apply string-append (map x->string (list a sep b))))
""
(map fun lst)))
(mapconcat values '(one "two" three) '-)
===>
"one-two-three"
(mapconcat square '(2 3 4) '---)
===>
"4---9---16"