[ Return the first and last element in the list Scheme ]
Pretty straightforward question. My initial approach was to define another procedure to find the last element of lst within first-last. After finding the last element I appended it with the first element of lst (car lst). This is how append works. (append list1 list2) e.g., (append '(1 2 3) '(2 1 5)) -> (1 2 3 2 1 5) I'm wondering if the problem is just with my syntax but I am not sure.
(define (first-last lst)
(define (last lst)
(cond ((null? (cdr lst))(car lst))
(else (last (cdr lst)))))
(append(car lst)(last lst)))
The error occurs in the
(append(car lst)(last lst)))
"mcar: contract violation
expected: mpair?
given: 1"
This is my first question on stack, so I'm sorry if the question is not presented in the correct way.
Answer 1
append
is only for joining two or more lists. Here, though, you're not joining existing lists, but building a list from two elements. For that, use list
:
(list (car lst) (last lst))
Answer 2
If you can use match
, a neat solution is possible:
(define first-last
(lambda (x)
(match x
((first rest ... last)
(list first last))
((only) (list only only))
(_ #f))))
Of course, you could return something other than #f
in the catch-all clause.