Sysop: | Amessyroom |
---|---|
Location: | Fayetteville, NC |
Users: | 23 |
Nodes: | 6 (0 / 6) |
Uptime: | 49:51:20 |
Calls: | 583 |
Files: | 1,138 |
Messages: | 111,303 |
You have a list contain both strings and numbers.
Generate a new list in which the adjacent strings
have been concatenated.
Scheme
(define (merge-strings List)
(reverse
(fold
(lambda (e accum)
(if (and (string? e) (pair? accum) (string? (car accum)))
(cons (string-append (car accum) e) (cdr accum))
(cons e accum)))
'()
List)))
(merge-strings '("1" "2" 3 4 "5" "6" 7 8 "9"))
===>
("12" 3 4 "56" 7 8 "9")
(defun merge-strings (list)
(loop while list
if (stringp (car list)) collect
(apply #'concatenate 'string
(loop while (stringp (car list))
collect (pop list)))
else collect (pop list)))
B. Pym wrote:
You have a list contain both strings and numbers.
Generate a new list in which the adjacent strings
have been concatenated.
Scheme
(define (merge-strings List)
(reverse
(fold
(lambda (e accum)
(if (and (string? e) (pair? accum) (string? (car accum)))
(cons (string-append (car accum) e) (cdr accum))
(cons e accum)))
'()
List)))
(merge-strings '("1" "2" 3 4 "5" "6" 7 8 "9"))
===>
("12" 3 4 "56" 7 8 "9")
(defun merge-strings (list)
(loop while list
if (stringp (car list)) collect
(apply #'concatenate 'string
(loop while (stringp (car list))
collect (pop list)))
else collect (pop list)))
Gauche Scheme
;; Doesn't cause an error is list is empty.
(define (car~ xs) (and (pair? xs) (car xs)))
(define (merge-strings xs . r)
(while (pair? xs)
(push! r
(if (string? (car xs))
(let f ()
(if (string? (car~ xs)) (string-append (pop! xs) (f)) ""))
(pop! xs))))
(reverse r))
B. Pym wrote:
B. Pym wrote:
You have a list contain both strings and numbers.
Generate a new list in which the adjacent strings
have been concatenated.
Scheme
(define (merge-strings List)
(reverse
(fold
(lambda (e accum)
(if (and (string? e) (pair? accum) (string? (car accum)))
(cons (string-append (car accum) e) (cdr accum))
(cons e accum)))
'()
List)))
(merge-strings '("1" "2" 3 4 "5" "6" 7 8 "9"))
===>
("12" 3 4 "56" 7 8 "9")
(defun merge-strings (list)
(loop while list
if (stringp (car list)) collect
(apply #'concatenate 'string
(loop while (stringp (car list))
collect (pop list)))
else collect (pop list)))
Gauche Scheme
;; Doesn't cause an error is list is empty.
(define (car~ xs) (and (pair? xs) (car xs)))
(define (merge-strings xs . r)
(while (pair? xs)
(push! r
(if (string? (car xs))
(let f ()
(if (string? (car~ xs)) (string-append (pop! xs) (f)) ""))
(pop! xs))))
(reverse r))
Shorter.
(define (merge-strings List)
(fold-right
(^(e accum)
(cons
(if (and (string? e) (string? (car~ accum)))
(string-append e (pop! accum))
e)
accum))
()
List))