Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Applying A List of Functions to a Number

Tags:

scheme

racket

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.

like image 636
Jon Tan Avatar asked Mar 21 '12 02:03

Jon Tan


1 Answers

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)
like image 66
Óscar López Avatar answered Nov 15 '22 08:11

Óscar López