user3451848
user3451848

Reputation:

Scheme - using apply

I received the following exercise as homework. I sat on it for hours without any success, so I have no choice but to use your help.

Examples:

(define m1 (cons "fixNumber" (lambda () 42)))

(define m3 (cons "add" (lambda (x y) (+ x y))))

(define myobj (create-obj (list m1 m2 m3)))

(myobj "fixNumber" '()) ;; => 42

(myobj "add" '(1 2)) ;; => 3

(myobj "myMethod" '()) ;; => "Error: no such method" 

Upvotes: 0

Views: 180

Answers (1)

uselpa
uselpa

Reputation: 18917

This should do:

(define (create-obj mlist)
  (lambda (method parms)
    (let ((func (assoc method mlist)))
      (if func
          (apply (cdr func) parms)
          "Error: no such method"))))

Upvotes: 1

Related Questions