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]"
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"
Shorter:
(define (mapconcat fun lst sep)
(string-join (map (compose x->string fun) lst) (x->string sep)))
Sysop: | Keyop |
---|---|
Location: | Huddersfield, West Yorkshire, UK |
Users: | 403 |
Nodes: | 16 (2 / 14) |
Uptime: | 44:12:43 |
Calls: | 8,407 |
Calls today: | 2 |
Files: | 13,171 |
Messages: | 5,905,028 |