lens implemented in rust
Review
optics describes how to construct a single value.Traversal
can access the multiple substructures.Prism
can access the substructure may exist.Lens
can access the substructure must exist.access the substructure
```rust
fn test() -> Option<()> {
let mut nested: Result
let mut x = (1, (2, (3, 4)));
*optics!(_1._1._1).view_mut(&mut x) *= 2;
assert_eq!(optics!(_1._1._1).view(x), 8);
let mut x: (_, Result<_, ()>) = (1, Ok((2, 3)));
*optics!(_1._Ok._1).pm_mut(&mut x)? *= 2;
assert_eq!(optics!(_1._Ok._1).pm(x)?, 6);
let mut x = (1, vec![Some((2, 3)), None]);
optics!(_1.Mapped._Some._0)
.traverse_mut(&mut x)
.into_iter()
.for_each(|i| *i += 1);
assert_eq!(optics!(_1.Mapped._Some._0).traverse(x), vec![3]);
Some(())
} ```
derive lens for data types ```rust use lens_rs::*;
enum AnEnum
struct Foo { #[optic] a: i32, #[optic] b: i32, }
fn test() -> Option<()> { let x = optics!(Some.B).review(Foo { a: 3, b: 2, }); asserteq!(optics!(_Some.B.b).pm(x)?, 2);
Some(())
} ```
assume a type T may have substructure that the type is i32
.
```rust
fn bar
fn test() { let mut complex = (1, Ok((Err(2), 3))); bar(&mut complex, optics!(0)); bar(&mut complex, optics!(1.Err)); // do nothing bar(&mut complex, optics!(1.Ok.0.Ok)); // do nothing bar(&mut complex, optics!(1.Ok.0.Err)); bar(&mut complex, optics!(1.Ok.1)); assert_eq!(complex, (3, Ok((Err(4), 5)))); } ```
assume a type T must have a field .a
.
```rust
fn withfielda
let foo = Foo { a: "this is Foo".tostring(), b: () }; let bar = Bar { a: "this is Bar".tostring(), c: 0 };
println!("{}", withfielda(foo)); println!("{}", withfielda(bar)); ```