LeviySoft.Visor is an optics library for .NET
C# 9 introduced record types, which are a first-class implementation of immutable data types. While records are very useful for domain modeling, it can be pretty akward to modify deeply nested structures:
recordInnerItem(intId,stringName);recordItemWrapper(InnerItemItem, ...);recordWarehouse(ItemWrapperMain, ...);varwarehouse=newWareHouse(..);//We want to modify Id of InnerItem herevarwarehouse2=warehousewith{Main=warehouse.Mainwith{Item=warehouse.Main.Itemwith{Id=42//Here is our new Id}}}This problem becomes more annoying with every new level of nesting,
and here optics come on the scene. The overall concept of optics
is to abstract accessing (and modifying) immutable data from
the data itself. Let's generate Lens optic for the case above and see,
how can we re-write our modification:
[Optics]partialrecordInnerItem(intId,stringName);[Optics(withNested:true)]partialrecordItemWrapper(InnerItemItem, ...);[Optics(withNested:true)]partialrecordWarehouse(ItemWrapperMain, ...);varwarehouse=newWareHouse(..);varwarehouse2=Warehouse.FocusMain.FocusItem.IdLens.Set(42)(warehouse);withNested controls "chained" Lens generation.
Lens is not the only optic on the table, with Prism for example you can
abstract over subtyping, with Traverse over enumerable structures etc.
- install
LeviySoft.VisorandLeviySoft.Visor.Gen - add
[Optics]attribute on your record and make your record partial
[Optics]partialrecordSample(intId,stringDescription);- now you can use
Samplestatic class containing optics:
varid=Sample.IdLens.Get(...);Sample.DescriptionLens.Set("replaced")(...);Visor comes with a useful set of optics for manipulating values at nullable anr/or collection properties.
Although System.Collections.Immutable is supported I strongly recommend using language-ext's immutable collections
because standart ones breaks value equality of records.
Here is a brief example of using build-in optics:
[Optics]internalpartialrecordInnerItem(intId,stringName);[Optics]internalpartialrecordAux(stringComment,IImmutableList<string>Tags);[Optics(withNested:true)]internalpartialrecordItemWrapper(InnerItemItem,Aux?Aux);[Optics(withNested:true)]internalpartialrecordWarehouse(ItemWrapperMain);varwarehouse=newWarehouse(newItemWrapper(newInnerItem(1,"Default"),newAux("test",ImmutableList.Create("tag1","tag2"))));vartelescope=Warehouse.FocusMain.AuxLens.NotNull().Compose(Aux.TagsLens).Compose(Property.IImmutableList.First<string>());varwarehouse2=telescope.Set("updated_tag")(warehouse);//Now warehouse2.Main.Aux?.Tags is ("updated_tag", "tag2")- Prism
- Traverse
- Fold
- Iso
LeviySoft.Visor is an independently maintained fork of Tinkoff.Visor and is not related to Tinkoff in any kind.