0

Suppose we have a list of pairs, ex. '((a . true) (b . false))

How do I declare it within a function and use the variable to do something else? (say using it to evaluate boolean expressions like (a and b))

Currently I have

  (define foo2
    (λ (xs)
      (let ((car (first xs)) (cdr (first xs)))
        xs)
      (eval (and (car (first xs))  ; check a is #t
                #t)
             )))

which works for when a list consists of a single element, example:

> (foo2 '((a . true)))
#t

but I want it to recursively (or other methods) to take in multiple variables like '((a . true) (b . false)).

I tried the usual way like

(cons (eval (and (car (first xs)) #t)) (foo2 (rest xs)))

but does not work as wanted.

And is this possible?

  (define foo3
    (λ (xs)
      (let ((car (first xs)) (cdr (first xs)))
        xs)
      (eval (and a #t)))) ; a is what we defined to be #t
Chase
  • 93
  • 10
  • https://docs.racket-lang.org/reference/let.html#%28form._%28%28quote._~23~25kernel%29._let-values%29%29 – ceving Feb 26 '16 at 10:00
  • 1
    If you're trying to evaluate boolean expressions like `(a and b)`, then you probably shouldn't be using `eval`. Your list of pairs `'((a . #true) (b . #false))` is an association list representing the environment, right? But `eval` doesn't work like that. Use something like `dict-ref` or `assoc` instead. If `xs` is your list of pairs, then to get the value of `a` (which is `#true`), you can use `(dict-ref xs 'a)`. To get the value of `b` (which is `#false` here), you can use `(dict-ref xs 'b)`. Using `eval` like this won't work. – Alex Knauth Feb 26 '16 at 14:10
  • Your binding to `car` and `cdr` makes that incomprehensible to old farts like me. – molbdnilo Feb 26 '16 at 15:11
  • ahhh `dict-ref` was what I needed.. everything works now, thanks!! – Chase Feb 26 '16 at 18:49

0 Answers0