如何将列表中的每个元素应用于方案中的函数? [英] How can I apply each element in a list to a function in scheme?

查看:79
本文介绍了如何将列表中的每个元素应用于方案中的函数?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

函数applyToAll假定接收一个函数和一个List,然后乘列表的车,并将每个元素应用于功能.

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) )  

它将返回

(1 4 9)

相反,它返回:函数调用:在圆括号后应有一个函数,但已收到(列表1 2 3)

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?

谢谢

推荐答案

听起来您正在尝试实现地图".

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))))

正确的申请方法是:

(function arg0 arg1 ... argn)

您需要将f应用于列表中的每个元素. 这应该工作:

You need to apply f to each element in the list. this should work:

(cons(f(car L))(applyToAll f(cdr L))))

(cons (f (car L)) (applyToAll f (cdr L))))

第一个elemnet:

the first elemnet:

(car L)

列表的其余部分:

(cdr L)

gl

这篇关于如何将列表中的每个元素应用于方案中的函数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆