Reputation: 11
i want to change the value of number of a list,but it always shows that
set!: not an identifier in: (car (cdr (car a)))
i don't know what to do, anyone who can help me? thanks advanced!
(define a (list (list burnie 236.67) (list launceston 163.66)))
(define-syntax-rule (myset-car! lst val)
(if (not (list? lst))
lst
(set! lst (cons val (cdr lst)))))
(define update_gn
(lambda (a)
(cond
((null? a) #t)
(else
(myset-car! (car (cdr (car a))) (+ (car (cdr (car a))) (car new_gn)))
(update_gn (cdr a) )))))
Upvotes: 1
Views: 1662
Reputation: 48735
You cannot mutate pairs in #!racket (the language) since they made them immutable after deviating from Scheme. If you use a Scheme language in Racket (the application) you will be able to do this:
#!r6rs
(import (rnrs) (rnrs mutable-pairs))
(define test-list (list (list 'burnie 236.67) (list 'launceston 163.66)))
(define new-gn (list 10)) ; I'm not sure what this actually is, but tyhe procedures expect it to be a pair with a numeric car.
(define (update-gn lst)
(cond
((null? lst) #t)
(else
(set-car! (cdar lst) (+ (cadar lst) (car new-gn)))
(update-gn (cdr lst)))))
(update-gn test-list)
test-list ; ==> ((burnie 246.67) (launceston 173.66))
Now, you actually do have mutable pairs in #!Racket (the language), but you need to use mcons
, mcar
and mcdr
and they are mpair?
and not pair?
. You'll need to make you own cadar
like this (define mcadar (compose mcar mcdr mcar))
and most of the higher order functions you use do not support them so you have to make your own.. This makes it very painful and it's like that by design. I usually change language to R6RS (Standard Scheme) the second I find out I need mutable pairs.
Upvotes: 2
Reputation: 18917
If you want to do updates in this way, you should really use vectors, not lists.
With lists, you should use a more functional approach, where you use higher-order functions to iterate over lists, and return new lists. For example, to add 10 to every second element of each sublist:
> (define a (list (list 'burnie 236.67) (list 'launceston 163.66)))
> a
'((burnie 236.67) (launceston 163.66))
> (map (lambda (lst) (list (car lst) (+ (cadr lst) 10))) a)
'((burnie 246.67) (launceston 173.66))
> a ; has not been modified
'((burnie 236.67) (launceston 163.66))
> (set! a (map (lambda (lst) (list (car lst) (+ (cadr lst) 10))) a))
> a ; has been modified
'((burnie 246.67) (launceston 173.66))
Upvotes: 0