Writing flatten method in Scheme

前端 未结 3 613
滥情空心
滥情空心 2020-12-21 13:03

I have been working on the following function flatten and so far have it working for just lists. I was wondering if someone could provide me with some insight on how to get

相关标签:
3条回答
  • 2020-12-21 13:43
    (define (flatten l)
      (cond
        [(empty? l) empty]
        [(list? l)
         (append (flatten (first l))
                 (flatten (rest l)))]
        [else (list l)]))
    
    0 讨论(0)
  • 2020-12-21 13:59

    This does what you want, without requiring append, making it o(n). I walks the list as a tree. Some schemes might throw a stack overflow error if the list is too deeply nested. In guile this is not the case.

    I claim no copyright for this code.

    (define (flatten lst)
      (let loop ((lst lst) (acc '()))
        (cond
         ((null? lst) acc)
         ((pair? lst) (loop (car lst) (loop (cdr lst) acc)))
         (else (cons lst acc)))))
    
    0 讨论(0)
  • 2020-12-21 14:02

    Here's one option:

    (define (flatten x)
      (cond ((null? x) '())
            ((pair? x) (append (flatten (car x)) (flatten (cdr x))))
            (else (list x))))
    
    0 讨论(0)
提交回复
热议问题