Suppose I have a struct with many fields:
(struct my-struct (f1 f2 f3 f4))
If I am to return a new struct with f2
updated, I have to rephrase every other fields:
(define s (my-struct 1 2 3 4))
(my-struct (my-struct-f1 s)
(do-something-on (my-struct-f2 s))
(my-struct-f3 s)
(my-struct-f4 s))
Which is redundant and would be a source of bugs if I update the number of the fields or changed their orders.
I really wonder if there's a such way I can update a specific field for a struct like:
(my-struct-f2-update (my-struct 1 2 3 4)
(lambda (f2) (* f2 2)))
;; => (my-struct 1 4 3 4)
Or I can just set them to a new value as:
(define s (my-struct 1 2 3 4)
(my-struct-f2-set s (* (my-struct-f2 s) 2))
;; => (my-struct 1 4 3 4)
Notice, this is not mutating s
here; my-struct-f2-update
and my-struct-f2-set
should be just returning a copy of s
with f2
field updated.
In Haskell I know the 'lens' library that does this job. I'm just wondering if there are some similar ways that I can adopt for racket. Thanks.