问题
The function applyToAll is suppose to take in a function and a List, then take the car of the list and apply each element to the fuction.
This is what I have worked out so far:
(define applyToAll(lambda (f L)
(cond
((null? L) '())
(#t (cons (L) (applyToAll f(car L))))
)))
I'm not sure what I am doing wrong. A fuction call would look like
(applyToAll (lambda (n) (* n n)) '(1 2 3) )
and it would return
(1 4 9)
Instead it returns: function call: expected a function after the open parenthesis, but received (list 1 2 3)
Any help as to why my code is not working?
Thanks
回答1:
It sounds like you are trying to implement 'map'.
The error you are getting is because you are calling a list as though it's a funtion. (L) () this means funtion call in scheme - scheme doc
You are making the same error here:
(#t (cons (L) (applyToAll f(car L))))
the right way to apply is:
(function arg0 arg1 ... argn)
You need to apply f to each element in the list. this should work:
(cons (f (car L)) (applyToAll f (cdr L))))
the first elemnet:
(car L)
the rest of the list:
(cdr L)
gl
来源:https://stackoverflow.com/questions/42840761/how-can-i-apply-each-element-in-a-list-to-a-function-in-scheme