user2726232
user2726232

Reputation: 131

List of procedures in scheme

In scheme, I would like to be able to have a list of procedures that I could use on lists of numbers via map.

For example, say I have the procedure

(define (overten? x) (> x 10))

Why does this work when called with (foo '(1 2 11 12) '()) ?

(define (foo lst proc)
    (map overten? lst)
)

But this gives an error called with (foo '(1 2 11 12) '(overten?)) ?

(define (foo lst proc)
    (map (car proc) lst)
)

With the error being

The object overten? is not applicable.

Upvotes: 0

Views: 996

Answers (2)

Sylwester
Sylwester

Reputation: 48735

'(overten?) is not a list with procedures. It's a list with a symbol that has nothing to do with procedures bound to that name in any scope

You need to think evaluation:

overten? 
; ==> {procedure overten? blabla} 
;     (a implementation dependent representation of a procedure object
'overten 
; ==> overten? 
;     (just a symbol with name "overten?", nothing to do with the procedure object above)
(list overten? 'overten?) 
; ==> ({procedure overten? blabla} overten)
      a list where the first element is a procedure and the second a symbol with name "overten?"


(define another-name-quoted 'overten?) 
; ==> undefined
; 'overten? evaluated to a symbol, them bound to another-name-quoted
(define another-name overten?)         
; ==> undefined
; overten? evaluated to a procedure, then bound to another-name

The procedure overten? is not more overten? than it is another-name. Here is an example where we use lists of procedures. It's an implementation of the compose procedure:

(define (my-compose . procs)
  (let* ((rprocs (if (zero? (length procs))
                     (list values)
                     (reverse procs)))
         (proc-init (car rprocs))
         (proc-list (cdr rprocs)))
    (lambda args
      (foldl (lambda (proc acc)
               (proc acc))
             (apply proc-init args)
             proc-list))))

(define sum-square-sub1-sqrt
  (my-compose inexact->exact
              floor
              sqrt
              sub1
              (lambda (x) (* x x))
              +))

(sum-square-sub1-sqrt 1 2 3) ; 5

Upvotes: 0

coredump
coredump

Reputation: 38789

Because '(overten?) is a list containing a symbol. Only if you evaluated overten? you would get back the procedure. You need to write (list overten?) so that arguments to list are evaluated (unlike quote).

See Why does Scheme have both list and quote?

Upvotes: 2

Related Questions