views:

56

answers:

2

Hi,

I'm looking for a function in Scheme to replace a element in an equation by a value.

Exemple : '(+ a b c a) with (1 2 3) should give me '(+ 1 2 3 1). (I don't want to resolve the equation, it was just an exemple)

Basically, I want to say that a=1, b=2, c=3

To proceed, I extract the variables of my first list in another list. Then, I received the expected values in another list. Now, I want to assign values to variables.

Any hints on how I proceed? Thanks a lot.

+3  A: 

You can use an "association list" of mappings that looks like ((a 1) (b 2) (c 3)).

assq can retrieve the matching pair. So, for everything in your original list, you can look it up using assq and then replace it.

So:

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

Would take a list and an association list and replace everything in the original list with its replacement (if there is one).

erjiang
Thanks. I'm gonna give it a try!
esylvestre
Allright, exactly what I was looking for. Thanks a lot! I'm gonna mark your answer as resolved tomorrow.
esylvestre
+1  A: 

Ain't this what let do?

> (let ((a 1) (b 2) (c 3))
     (+ a b c b))
=> 8

If you don't want to evaluate the expression:

> (let ((a 1) (b 2) (c 3))
    `(+ ,a ,b ,c ,a))
=> (+ 1 2 3 1)
Vijay Mathew
Hum, I'm gonna try it to see if it works in my case.
esylvestre