I want to make a list of squares. I can do it with following code:
(define (makelistsq n)
(define outlist '())
(for ((i n))
(set! outlist (append outlist (list (* i i))))
)
outlist
)
(makelistsq 5)
Output:
'(0 1 4 9 16)
However, I have seen that often cons and car keywords are used to create and add to lists. Does that method has any advantage over appending as above? So, is following better or same as above:
(define (makelistsq2 n)
(define outlist '())
(for ((i n))
(set! outlist (cons (* i i) outlist))
)
(reverse outlist)
)
Thanks for your answers/comments.
Edit: on this page Cons element to list vs cons list to element in Scheme it is mentioned that all use of append is wrong:
For those rare occasions where you need to add one element at the end (and believe me, doing so generally means that you're thinking the algorithm wrong) you can use append