I am flying blind on scheme, and I feel like once I answer this question the rest of my homework should progress smoothly.
I’m defining a function that takes a list as its sole argument, then returns the same list with the first element added to the rest. For instance:
(addFirst ‘(4 3 2 1)) => (8 7 6 5)
I have a feeling that I should be using the map and car functions here… but I just can’t seem to get it exactly right. My current version of this code looks like:
(define (addlist x) ;adds the first element of a list to all other elements
(define a (car x)) ;a is definitely the first part of the list
(map (+ a) x)
)
How can I make the addition function work this way? Obviously I can’t provide a list as a parameter, but should I be using car again or recursion?
Okay, for posterity, here’s the completed, correct, formatted code:
(define (addlist x) ;adds the first element of a list to all other elements
(define a (car x)) ;a is definitely the first part of the list
(map (lambda (y) (+ a y)) x)
)
Map takes a function and n lists. So you need to transform (+ a) into a function that takes one argument (as you want to map over one list).