listschemelispeval

Scheme evaluation of list


I wrote a simple intersection function on two lists:

(define (intersection l1 l2)
  (if (null? l1) '()
      (if (member (car l1) l2)
          (cons (car l1) (intersection (cdr l1) l2))
          (intersection (cdr l1) l2))))

But I can't get replace this code so that (intersection (cdr l1) l2) only appears once as in:

(define (intersection l1 l2)
  (if (null? l1) '()
      (let (appel '(intersection (cdr l1) l2))
        (if (member (car l1) l2)
            (cons (car l1) appel)
            appel))))

I try also to replace appel with (eval appel) but it didn' work.


Solution

  • I try also to replace appel with (eval appel) but it didn' work.

    The expression (eval '(intersection (cdr l1) l2)) will eventually evaluate l1 and l2, which are free variables in the expression. You didn't show which error you had but you probably encountered something like this:

    reference to undefined identifier: l1
    

    Function calls do not capture the current lexical environment; eval is not special here, it doesn't have access to the bindings that are present in the source code when it is being executed.