Home > Back-end >  Where is the argument coming from?
Where is the argument coming from?

Time:10-02

You can notice the v in the lambda in the function body, where is the v coming from, what it is based on?

(define (cached-assoc xs n)
  (letrec ([memo (make-vector n #f)]
           [acc 0]
           [f (lambda(x)
                (let ([ans (vector-assoc x memo)])
                  (if ans
                      (cdr ans)
                      (let ([new-ans (assoc x xs)])
                       (begin
                         (vector-set! memo acc (cons x new-ans))
                         (set! acc (if (= (  acc 1)) 0 (  acc 1)))
                         new-ans)))))])
  (lambda (v) (f v))))

CodePudding user response:

The whole expression is returning a lambda as a result, and in that lambda there's a formal parameter named v. It doesn't have a value yet, you'll need to call the lambda to bind a value to v and produce a result (assuming the code is working):

((letrec ([memo (make-vector n #f)] ; notice the extra opening `(`, we want to call the returned lambda
          [acc 0]
          [f (lambda(x)
               (let ([ans (vector-assoc x memo)])
                 (if ans
                     (cdr ans)
                     (let ([new-ans (assoc x xs)])
                       (begin
                         (vector-set! memo acc (cons x new-ans))
                         (set! acc (if (= (  acc 1)) 0 (  acc 1)))
                         new-ans)))))])
   (lambda (v) (f v)))
 10) ; <- the value 10 gets bound to `v`

However, your code isn't right. You are referring to variables named n and xs, but they are not defined anywhere and need a value of their own. The procedure vector-assoc doesn't exist. Also, the lambda at the end is redundant, you could simply return f, there's no need to wrap it in an additional lambda. Finally: you should define the whole expression with a name, it'll make it easier to call it.

I won't go into more details because first you need to fix the function and make it work, and is not clear at all what you want to do - but that should be a separate question.

  • Related