In: Computer Science
I am writing a scheme function that pairs an element to every element in a list, and I have the following code so far:
(define (pair-element e l)
(cond ((null? l) (list e))
(else (cons e (car l)) (pair-element (cdr l)))))
(pair-element 4 `(4 3 5))
What is my error? I'm getting a pair element mismatch when I run it. I need to do this without using built-in functions. Thanks!
1.(define (pair-element e l)
2.(cond ((null? l) (list e))
3.(else (cons e (car l)) (pair-element (cdr l)))))
Your program is calling function (pair-element) with just one argument at line number 3. It takers two arguments "e" and "l".
Second error is that your program will always return only list of single element. Not all pairs. Cons the elements as shoen in below code.
Correct Code:
(define (pair-element e l)
(cond ((null? l) '()) ;;if list empty should return empty list not
list which contains e
(else (cons (cons e (list (car l))) (pair-element e (cdr l))))))
;;else pair element with each member of list.
Snapshot of Code and Output: