How to Reverse a List?

前端 未结 7 2178
有刺的猬
有刺的猬 2020-12-03 06:28

What is the function to a list in Scheme? It needs to be able to handle nested lists.

So that if you do something like (reverse \'(a (b c d) e)) you\'ll

7条回答
  •  攒了一身酷
    2020-12-03 06:38

    I used a code similar to insert sort

    (define deep-rev-list
      (lambda (l)
         (cond ((null? l) (quote ()))
               ((atom? (car l))
                 (swap-till-end (carl) (deep-rev-list (cdr l))))
               (else
                 (swap-till-end (deep-rev-list (car l)) (deep-rev-list (cdr l)))))))
    
    
    (define swap-till-end
       (lambda (elm lst)
          (cond ((null? lst) (cons elm '()))
                (else
                   (cons (car lst) (swap-till-end elm (cdr lst)))))))
    
    (define atom?
      (lambda (x)
        (and (not (null? x)) (not (pair? x)))))
    

    I am reproducing it from memory. There may be some errors. Will correct the code if thats the case. But the technique used is similar to the commandments for nested lists given in THe Little Schemer :). I checked it in DrRacket

    (deep-rev-list '((1 2) (3) ((4 5)))) returns (((5 4)) (3) (2 1))

提交回复
热议问题