I want to write my own append , for appending an element to an existing list .
I’ve written the following :
(define (appendElem llist elem)
(if (null? llist)
elem
(cons (car llist) (appendElem (cdr llist) elem))))
But when I do this :
(appendElem (list 1 2 30) 11)
I get :
(1 2 30 . 11)
So the question is , why (1 2 30 . 11) and not (1 2 30 11) ?
Thanks
EDIT:
Fixed :
(define (appendElem llist elem)
(if (null? llist)
(list elem)
(cons (car llist) (appendElem (cdr llist) elem))))
Think about what you want your base case to be. Do you want just
elem, or do you want a list with the single itemelem? There is a difference. If the want the latter, you will need to fix your base case in the code.In other words, do you want
(appendElem '() 42)to return42, or(42)? Think carefully about the answer to that question, then think about what the consequence of each choice is.By the way, while you can implement
appendElemas a toy, you’ll soon realise that that function has O(n) runtime. So do not build lists using this approach! The standard way to build a list is toconsitems to it, thenreversethe final resulting list.