How can I apply each element in a list to a function in scheme?

隐身守侯 提交于 2019-12-25 05:14:15

问题


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

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!