Applying A List of Functions to a Number

▼魔方 西西 提交于 2019-12-06 03:57:02

问题


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.


回答1:


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

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

EDIT :

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

Use it like this:

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



回答2:


Another clever way to apply one function after another is to fold with compose like so:

(define functions (list add1 abs list))
((foldl compose1 values functions) -5) 
;which reduces to (list (abs (add1 (values -5)))) 
;which reduces to '(4)


来源:https://stackoverflow.com/questions/9797991/applying-a-list-of-functions-to-a-number

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