a tail-recursion version list appending function

后端 未结 5 2151
猫巷女王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:29

    Well it is possible to write a tail-recursive append-element procedure...

    (define (append-element lst ele)
      (let loop ((lst (reverse lst))
                 (acc (list ele)))
        (if (null? lst)
            acc
            (loop (cdr lst) (cons (car lst) acc)))))
    

    ... but it's more inefficient with that reverse thrown in (for good measure). I can't think of another functional (e.g., without modifying the input list) way to write this procedure as a tail-recursion without reversing the list first.

    For a non-functional answer to the question, @WillNess provided a nice Scheme solution mutating an internal list.

提交回复
热议问题