2021-11-05 14:22:59 +00:00
|
|
|
# bad optics
|
|
|
|
|
|
|
|
ergonomic no-macro lenses for rust
|
|
|
|
|
|
|
|
## example
|
|
|
|
|
|
|
|
```rust
|
|
|
|
use bad_optics::{
|
2021-11-05 15:28:34 +00:00
|
|
|
lenses::{_0, _1},
|
|
|
|
*,
|
2021-11-05 14:22:59 +00:00
|
|
|
};
|
|
|
|
|
|
|
|
fn main() {
|
|
|
|
let a = ((1, 2), 3);
|
|
|
|
|
2021-11-05 15:28:34 +00:00
|
|
|
// use view to access inside the tuple
|
|
|
|
let res = view(_0, a);
|
|
|
|
assert_eq!(res, (1, 2));
|
|
|
|
|
|
|
|
let res = view(_1, a);
|
|
|
|
assert_eq!(res, 3);
|
|
|
|
|
|
|
|
// you can combine lenses
|
2021-11-05 14:22:59 +00:00
|
|
|
let lens = _0 + _1;
|
|
|
|
|
|
|
|
// use the view function to access
|
|
|
|
let res = view(lens, a);
|
|
|
|
assert_eq!(res, 2);
|
|
|
|
|
2021-11-05 15:28:34 +00:00
|
|
|
// you can also call the lens as a function
|
2021-11-05 14:22:59 +00:00
|
|
|
let res = lens(a);
|
|
|
|
assert_eq!(res, 2);
|
|
|
|
|
|
|
|
// call the over function to modify the value
|
|
|
|
let a = over(lens, a, |v| v + 1);
|
|
|
|
assert_eq!(a, ((1, 3), 3));
|
|
|
|
|
|
|
|
// call the set function to set the value
|
|
|
|
let a = set(lens, a, 5);
|
|
|
|
assert_eq!(a, ((1, 5), 3));
|
|
|
|
|
2021-11-05 15:28:34 +00:00
|
|
|
// you can also call the lens as a function to modify the value
|
2021-11-05 14:22:59 +00:00
|
|
|
let res = lens(a, |v| v + 1);
|
|
|
|
assert_eq!(res, ((1, 3), 3));
|
|
|
|
}
|
|
|
|
```
|