What is a Lens and how to use it
masterA Lens is a type that pairs a getter and a non-mutating setter for a data structure. It allows you to view and update specific parts of a structure immutably.
Lenses provide three primary capabilities:
get: Retrieves a reference to a part of the structure.set: Returns a new version of the structure with the specified value updated.over: Applies a function to the value retrieved by the getter and returns a new version of the structure with the result.
Lenses are also composable, allowing you to perform immutable updates to deeply nested data by composing multiple lenses together.
trait Lens<S, A> {
fn over(s: &S, f: &Fn(Option<&A>) -> A) -> S {
let result: A = f(Self::get(s));
Self::set(result, &s)
}
fn get(s: &S) -> Option<&A>;
fn set(a: A, s: &S) -> S;
}