a tail-recursion version list appending function

后端 未结 5 2147
猫巷女王i
猫巷女王i 2020-12-04 01:44

i see several examples of implementing append an element to a list, but all are not using tail recursion. how to implement such a function in a

5条回答
  •  暖寄归人
    2020-12-04 02:05

    This is a functional, tail recursive append-elt using continuations:

    (define (cont-append-elt lst elt)
      (let cont-loop ((lst lst)
                      (cont values))
        (if (null? lst)
            (cont (cons elt '()))
            (cont-loop (cdr lst)
                       (lambda (x) (cont (cons (car lst) x)))))))
    

    Performance-wise it's close to Will's mutating one in Racket and Gambit but in Ikarus and Chicken Óscar's reverse did better. Mutation was always the best performer though. I wouldn't have used this however, but a slight version of Óscar's entry, purely because it is easier to read.

    (define (reverse-append-elt lst elt)
      (reverse (cons elt (reverse lst))))
    

    And if you want mutating performance I would have done:

    (define (reverse!-append-elt lst elt)
      (let ((lst (cons elt (reverse lst))))
         (reverse! lst)
         lst))
    

提交回复
热议问题