i am fairly new to Scheme and,i was thinking of a way to cube every number in a given list recursively so far this is what i have:
(define (cube-it-list lst)
(cond [(empty? lst) empty]
[else (cons (cube-it (first lst))
(cube-it-list (rest lst)))]))
but every time I execute the program i get an error and i'm not sure why that is can anyone help or come up with a better more efficient way to do this.
Have you defined the function cube-it? When I did, your code worked for me.
In any case, there is a construct in Scheme for precisely this sort of thing: making one list out of another by applying a transformation to each element. It's called map:
You've essentially reinvented it here, except map is not limited to a single transformation operation - you pass it the function you want to use as its first argument.
(Note, if you've been specifically told to implement a recursive solution, you should stick with your original code. map will use recursion internally, but using map means your own code doesn't need to involve any recursion for this case.)
The function looks fine, maybe the problem is in the
cube-it
procedure or in the way you're calling it. For example, this works:As for a "better more efficient way to do this", stick to @svk's answer and
map
over the input list, it's the idiomatic way to solve this type of problem that involves applying a function to each of the elements in an input list, to produce an output list with the results: