生成列表列表

Producing a list of lists

我正在尝试生成一个包含 *. 这是我目前所拥有的:

(define (position loc count)
  (cond [(empty? loc)empty]
    [else (cons (list (first loc) count)
                (position (rest loc) (add1 count)))]
    ))

所以:

(position (string->list "**.*.***..") 0) 

会产生:

(list
 (list #\* 0) (list #\* 1) (list #\. 2) (list #\* 3) (list #\. 4) (list #\* 5)     
 (list #\* 6) (list #\* 7) (list #\. 8) (list #\. 9))

基本上我想得到

(list (list (list #\* 0) (list #\* 1))
      (list (list #\* 3))
      (list (list #\* 5)(list #\* 6) (list #\* 7)))

我考虑过使用 foldr,但不确定是否可行。任何帮助将不胜感激。

尽管它不完全是一个 foldr 解决方案,您需要一个函数来根据先前的输入修改它的行为,以便对连续的星号字符进行分组。查看我在找到匹配项时使用布尔值来切换行为。

(define (combine-continuous char L)
  (let loop ((L L) (acc '()) (continuing? #t))
    (cond ((null? L) (list (reverse acc)))
          ((equal? (caar L) char)
           (if continuing?
               (loop (cdr L) (cons (car L) acc) #t)
               (cons (reverse acc) 
                     (loop (cdr L) (list (car L)) #t))))
          (else (loop (cdr L) acc #f)))))

(combine-continuous #\* (position (string->list "**.*.***..") 0))
=->
;Value 19: (((#\* 0) (#\* 1)) ((#\* 3)) ((#\* 5) (#\* 6) (#\* 7)))