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 gi开发者_JAVA百科ve 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.
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).
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)
精彩评论