Search code examples
listfunctional-programmingschemeracketsubstitution

Substitute values in Scheme lists


Suppose I have an arbitrary list representing Boolean expressions:

'(a and (b or c)) and another list of pairs representing the values of the literals

'((a . #t) (b . #f) (c . #t)))

What I want to do is replace the values in the first list using the values from the second list, and return a new list:

'(#t and (#f or #t))

So for example this code takes a list and an association list, and successfully replaces the values inside of it, though I'm trying to do the same thing given a list of conses instead of an association list. It works for '(a b) '((a 1) (b 2)) -> '(1 2), but I want to instead use '((a . 1) (b . 2)). Here is that code:

(define replace
    (lambda (ls a-list)
     (map (lambda (x)
            (let ((lookup (assq x a-list)))
              (if lookup
                  (cadr lookup)
                  x)))
          ls)))

Would anyone know how to do this? Thanks so much!


Solution

  • Something like this:

    (define bool '(a and (b or c)))
    (define pairs '((a . #t) (b . #f) (c . #t)))
    
    (define (value-for-key lst key)
      (cond ((empty? lst) 'none)
            ((eq? key (caar lst))
             (cdar lst))
            (#t (value-for-key (cdr lst) key))))
    
    (define (replace-bool lst vals)
      (cond ((empty? lst) lst)
            ((pair? (car lst)) (cons (replace-bool (car lst) vals)
                                     (replace-bool (cdr lst) vals)))
            (#t (let ((val-for-key (value-for-key vals (car lst))))
                    (if (not (eq? val-for-key 'none))
                        (cons val-for-key (replace-bool (cdr lst) vals))
                        (cons (car lst) (replace-bool (cdr lst) vals)))))))
    
    (replace-bool bool pairs)
    

    -> (#t and (#f or #t))

    First function is for searching in list of pairs key-value and returns value for given key or 'none, if that key isn't in that list.
    Second function goes through Boolean expression list. Each atomic element is searched in key-value list and if it's found, is replaced. If Boolean expression contains nested expressions, they are traversed recursively.