I am getting started with the basics of scheme right now. I came across an exercise where a procedure needs to be created which adds the element x that can be symbols or numbers in between the elements of a given list.
For example:
The procedure (tech 7 (list 23 24 25))
should result in (23 7 24 7 25)
.
So far I have only a theoretical approach. It aims at splitting up the given list in car
and cdr
and to combine cdr
with a newly created list of the element x thru append
.
(define (tech x lst)
(if (null? lst)
'()
(cons (car lst) (append (cons ('x) (* 'x (length cdr lst))
(cdr lst)))))
Can anybody tell me what is wrong with the code? It only returns errors...
There are several issues with your code:
append
, most of the time using cons
is the correct approach for building a list. 'x
by the length of the list? that doesn't make any sense.'x
with the value of the x
variable.x
.tech
inside tech
.This fixes all the issues, most of the original code had to be rewritten:
(define (tech x lst)
(cond ((null? lst) '()) ; base case: empty list
((null? (cdr lst)) lst) ; list with a single element
(else (cons (car lst) ; this is how we add
(cons x ; the element to the list
(tech x (cdr lst))))))) ; advance recursion
It works as expected:
(tech 7 '(23 24 25))
=> '(23 7 24 7 25)