简体   繁体   中英

Replace elements of a struct in Racket

Let's say that we have the following expression (band 'x (bor 'y 'z)), where band and bor boolean structs that have arg1 and arg2.

If I want to change the variables 'x and 'y to 'a and 'b by deep recursion on the expression, how can I do that?

There is a special form for functionally updating just some fields in a struct which is very nice to use where you have a lot of fields:

(struct person (name age occupation) #:transparent)
(define p (person "Per" 19 "Painter"))

(define (change-occupation p new-occupation)
  (struct-copy person p [occupation new-occupation]))

(change-occupation p "Programmer") ; ==> (person "Per" 19 "Programmer")

Of course this is just a fancy way of writing:

(define (change-occupation p new-occupation)
  (person (person-name p)
          (person-age p)
          new-occupation))

Now I don't know the names of your two structs but you may need to make a generic accessor unless one is subtype of the other:

(define (change-first obj new-value)
  (if (band? obj)
      (band new-value (band-second obj))
      (bor new-value (bor-arg2 obj))))

Or you can just have similar case analysis in your procedure.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM