Search code examples
schemeracketcons

How can I use CONS in reverse way?


Normally, we pass two arguments to cons, in RACKET

eg: (cons 23 '(1 2 3))

which outputs '(23 1 2 3)

Is there any procedure to do the following

(procedure '(1 2 3) 23) => '(1 2 3 23)


Solution

  • Try this:

    (append '(1 2 3) '(23))
    => '(1 2 3 23)
    

    That's fine for appending a single element. If you're planning to repeatedly add many elements at the end, it's better if you cons everything at the head and then reverse the list when you're done. Why? because using append for building an output list will quickly degenerate into an O(n^2) solution (see: Schlemiel the Painter's algorithm)