Sort a list in scheme

前端 未结 2 470
深忆病人
深忆病人 2021-01-22 22:49

I want to create function which sorts list. For example I have this list:

x1, x2, x3 .... xn

or

1, 2, 3, 4, 5, 6

2条回答
  •  迷失自我
    2021-01-22 23:00

    This is not really a sorting operation, more like a shuffling; here's another way to solve it. First, let's define the interleave procedure that alternates elements from two lists, returning a single list:

    (define (interleave l1 l2)
      (cond ((empty? l1) l2)
            ((empty? l2) l1)
            (else (cons (first l1)
                        (interleave l2 (rest l1))))))
    

    Now we take the original list and split-at the middle (this is a Racket-specific procedure); finally we interleave the two resulting lists, reversing the tail:

    (define (zippy lst)
      (let-values (((head tail) (split-at lst (quotient (length lst) 2))))
        (interleave head (reverse tail))))
    

    The above implementation IMHO is a bit more intuitive, and if you're working with Racket it doesn't require external libraries. It works as expected:

    (zippy '(1 2 3 4 5 6))
    => '(1 6 2 5 3 4)
    

提交回复
热议问题