Search code examples
aiohttp

How to include the same element (nbr. or symbol) between the elements of a list in scheme?


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...


Solution

  • There are several issues with your code:

    • You should avoid using append, most of the time using cons is the correct approach for building a list.
    • Why are you multiplying 'x by the length of the list? that doesn't make any sense.
    • You're confusing the symbol 'x with the value of the x variable.
    • You need to consider a third case for handling the last element, because the list doesn't end in x.
    • Last but not least: you forgot to call the recursion! it'll never work if you omit a call to 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)