document nested clauses and update example

This commit is contained in:
AlexKnauth 2015-12-05 00:33:32 -05:00
parent 67b5ae5421
commit a00bc4bf55

View File

@ -5,7 +5,9 @@
@title{Lenses for nested data}
@defform[(define-nested-lenses [base-id base-lens-expr] clause ...)
#:grammar ([clause [sub-id sub-lens-expr]])]{
#:grammar ([clause [sub-id sub-lens-expr
clause
...]])]{
A shorthand for defining composed lenses for nested data structures.
For example, if there is a @racket[top] struct containing a
@ -19,16 +21,27 @@ Will define @racket[top-middle-x-lens] and @racket[top-middle-y-lens]
as @racket[(lens-thrush top-middle-lens middle-x-lens)] and
@racket[(lens-thrush top-middle-lens middle-y-lens)].
Clauses can be nested within other clauses as well:
@lens-unstable-examples[
(struct/lens ball (mass position velocity) #:transparent)
(struct/lens position (x y) #:transparent)
(struct/lens velocity (x y) #:transparent)
(define-nested-lenses [ball-pos ball-position-lens]
[x position-x-lens]
[y position-y-lens])
(define-nested-lenses [ball-vel ball-velocity-lens]
[x velocity-x-lens]
[y velocity-y-lens])
(lens-view ball-vel-x-lens (ball 1 (position 2 3) (velocity 4 5)))
(lens-set ball-vel-x-lens (ball 1 (position 2 3) (velocity 4 5)) 1004)
(struct/lens game (player1 player2))
(struct/lens player (position score))
(struct/lens position (x y))
(define-nested-lenses [game-player1 game-player1-lens]
[score player-score-lens]
[position player-position-lens
[x position-x-lens]
[y position-y-lens]])
(define-nested-lenses [game-player2 game-player2-lens]
[score player-score-lens]
[position player-position-lens
[x position-x-lens]
[y position-y-lens]])
(define the-game (game (player (position 1 2) 5) (player (position 3 4) 6)))
(lens-view game-player1-score-lens the-game)
(lens-view game-player1-position-lens the-game)
(lens-view game-player1-position-x-lens the-game)
(lens-set game-player1-score-lens the-game 9005)
(lens-set game-player1-position-lens the-game (position 2 0))
(lens-set game-player1-position-x-lens the-game 3)
]}