Applying A List of Functions to a Number

2019-04-08 19:12发布

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.

标签: scheme racket
2条回答
Ridiculous、
2楼-- · 2019-04-08 19: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)
查看更多
时光不老,我们不散
3楼-- · 2019-04-08 19:45

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)
查看更多
登录 后发表回答