Question

I want to create a list of functions in Scheme. As I figured out it would be something like this

(define (sqr x) (* x x))
(define (dbl x) (* 2 x))
(define (add-5 x) (+ 5 x))

(define list-of-funs '(sqr dbl add-5))

but I wonder how I can call separate functions from the list. Is there a better way to define a list of functions and call them separately?

Was it helpful?

Solution

Yes, there is a better way. You should use list, rather than quoting:

(define list-of-funs (list sqr dbl add-5))

The reason for this is that '(sqr dbl add-5) produces a list of symbols, whereas (list sqr dbl add-5) produces a list of procedure objects. You can invoke procedure objects. You cannot invoke symbols.

You can access the functions individually, by using first, second, or third (from SRFI 1) to pick elements out of the list, e.g.,

((first list-of-funs) 49)    ; => 7

Or else you might decide you want to map through them, or whatever. e.g.,

(define (square-double-and-add5 x)
  (map (lambda (f) (f x)) list-of-funs))
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top