recursion - Adding a symbol to the end of a two element list in Scheme -


so far have

(define insert-3   (lambda (sym ls)     (cond       [(null? ls) '()]       [else (cons sym (insert-3 (caadr ls)))]))) 

i know caadr wrong, because doesn't exist in 2 element list. don't know how add symbol end of list.

assuming

sym 'c ls  '(a b) 

then result constructed by

> (cons 'a (cons 'b (list 'c))) '(a b c) 

or equivalent

> (cons 'a (cons 'b (cons 'c null))) '(a b c) 

so procedure needs cons each element until has consumed ls, , cons (list sym) or (cons sym null) @ point:

(define insert-3    (lambda (sym ls)      (cond        [(null? ls) (list sym)]        [else       (cons (car ls) (insert-3 sym (cdr ls)))]))) 

such that

   (insert-3 'c '(a b)) => (cons 'a (insert-3 'c '(b))) => (cons 'a (cons 'b (insert-3 'c '()))) => (cons 'a (cons 'b (list 'c))) 

which work length of list:

> (insert-3 'c '(a b)) '(a b c) > (insert-3 'e '(a b c d)) '(a b c d e) 

Comments

Popular posts from this blog

java.util.scanner - How to read and add only numbers to array from a text file -

rewrite - Trouble with Wordpress multiple custom querystrings -