将函数列表应用于数字 [英] Applying A List of Functions to a Number

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

问题描述

我知道 Scheme/Racket 中的函数(例如 map、foldr 和 filter)可以做一些很棒的事情,例如将函数应用于元素列表.

I understand that functions in Scheme/Racket like map, foldr, and filter, can do wonderful things like apply a function to a list of elements.

是否可以将函数列表应用于单个元素?

Is it possible to apply a list of functions to a single element?

我想生成每个函数产生的值,然后找到它们的最大值.谢谢.

I would like to generate the values produced by each of the functions, then find their maximum. Thank you.

推荐答案

对于第一部分,此过程会将函数列表应用于单个参数,假设所有函数仅接收一个参数.返回结果列表

For the first part, this procedure will apply a list of functions to a single argument, assuming that all the functions receive only one argument. A list with the results is returned

(define (apply-function-list flist element)
  (map (lambda (f)
         (f element))
       flist))

对于第二部分,在列表中找到最大值很简单.例如,如果元素是 2 并且函数列表是 (list sin cos sqr sqrt):

For the second part, finding the maximum in the list is simple enough. For example, if the element is 2 and the list of functions is (list sin cos sqr sqrt):

(apply max
 (apply-function-list (list sin cos sqr sqrt) 2))

这是另一种可能的解决方案,不使用 apply 并在单个过程中:

Here's another possible solution, without using apply and in a single procedure:

(define (max-list-function flist element)
  (foldr max -inf.0
         (map (lambda (f) (f element))
              flist)))

像这样使用它:

(max-list-function (list sin cos sqr sqrt) 2)

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

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