diff --git a/examples/main.rs b/examples/main.rs index 15838b4..f85cc05 100644 --- a/examples/main.rs +++ b/examples/main.rs @@ -31,5 +31,5 @@ fn main() { // you can also call the lens as a function to modify the value let res = lens(a, |v| v + 1); - assert_eq!(res, ((1, 3), 3)); + assert_eq!(res, ((1, 6), 3)); } diff --git a/examples/struct_fields.rs b/examples/struct_fields.rs new file mode 100644 index 0000000..a1c926e --- /dev/null +++ b/examples/struct_fields.rs @@ -0,0 +1,27 @@ +use bad_optics::lenses::*; + +#[derive(Debug, PartialEq, Clone)] +struct MyStruct { + hey: (u8, (u8, i32)), +} + +fn main() { + // make a lens for Hello + let hey = lens( + |hello: MyStruct| hello.hey, + |mut hello: MyStruct, v| { + hello.hey = v; + hello + }, + ); + + let my_struct = MyStruct { hey: (1, (2, -3)) }; + + // the thing we want to access + let thing = (my_struct, "hello"); + + // a lens that targets the -3 inside my_struct + let lens_that_targets_the_i32 = _0 + hey + _1 + _1; + + assert_eq!(lens_that_targets_the_i32(thing), -3); +} diff --git a/src/lenses/mod.rs b/src/lenses/mod.rs index 7a76145..12e0563 100644 --- a/src/lenses/mod.rs +++ b/src/lenses/mod.rs @@ -213,4 +213,28 @@ mod tests { let hello = Hello { hey: 8 }; assert_eq!(l(hello, |v| v + 1), Hello { hey: 9 }); } + + #[test] + fn convoluted_example() { + #[derive(Debug, PartialEq, Clone)] + struct Hello2 { + hey: (u8, (u8, i32)), + } + + // make a lens for Hello + let l = lens( + |hello: Hello2| hello.hey, + |mut hello: Hello2, v| { + hello.hey = v; + hello + }, + ); + + let thing = Hello2 { hey: (1, (2, -3)) }; + let thing = (thing, "hello"); + + let lens_that_targets_the_i32 = _0 + l + _1 + _1; + + assert_eq!(lens_that_targets_the_i32(thing), -3); + } } diff --git a/src/prisms/mod.rs b/src/prisms/mod.rs index 371f32b..d68601f 100644 --- a/src/prisms/mod.rs +++ b/src/prisms/mod.rs @@ -88,7 +88,4 @@ mod tests { assert_eq!(review(_Some, 3), Some(3)); assert_eq!(review(_None, ()), None::<()>); } - - #[test] - fn view_combination() {} }