简体   繁体   English

在球拍中实现全部应用功能

[英]Implementing apply-all function in racket

I am trying to write a function apply-all that is passed a list of functions and a number, and produces a list of the values of the functions when applied to that number 我正在尝试编写一个函数apply-all ,该函数apply-all传递一个函数列表和一个数字,并在应用于该数字时产生一个函数值的列表

For example, 例如,

(apply-all (list sqrt square cube) 4) => (2 16 64))

assuming that all functions have been previously defined 假设所有功能均已预先定义

I know how to write each function separately and how that would work but I am a little confused about how to go about doing this one and processing what functions are passed 我知道如何分别编写每个函数以及该函数如何工作,但是我对如何执行此函数和处理传递的函数有些困惑

You need to traverse the function list and, for each function in turn, apply it to the number parameter. 您需要遍历功能列表,然后针对每个功能依次将其应用于number参数。 The easiest way to do this is by using the map procedure: 最简单的方法是使用map过程:

(define (apply-all flist num)
  (map (lambda (f) (f num))
       flist))

(apply-all (list sqrt square cube) 4)
=> '(2 16 64)

Here's a way to do it that I like, using for/list : 这是一种我喜欢的方式,使用for/list

(define (apply-all fs n)
  (for/list ([f fs])
     (f n)))
(define (apply-all fs n)
  (cond
    ((null? fs) fs)
     (else (cons ((car fs) n) (apply-all ??? ???)))))

Is probably what you were supposed to write, if this was an assignment. 如果这是一项作业,可能是您应该写的。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM