Applying A List of Functions to a Number

爷,独闯天下 提交于 2019-12-04 08:26:34

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)

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