r/fsharp 4d ago

Validated Lenses

Now that F# supports nested record updates, are lenses still useful?
For simple immutable updates, maybe not:
{ person with Address.City = newCity }

But what if changing City can fail validation?

Writing one fallible setter is easy:
setCity : string -> Address -> Result<Address, Error>

Assuming the value arrives from a boundary rather than being an invariant we can enforce at construction, the interesting problem starts when that update sits several levels deep in a domain model.

How do those fallible updates compose without writing the plumbing again at every level?

In this video I explore that using validated lenses, essentially extending the setter side of a lens to return a Result, while keeping composition.

Do you still find lenses useful in modern F#, or have nested record updates mostly replaced them for you?

https://www.youtube.com/watch?v=fD51kHHRmsk

13 Upvotes

2 comments sorted by

1

u/funk_r 3d ago

I don't use Lenses anymore.

1

u/tblahosh 18h ago

I'm not sure I was in the recorded event, but I have been in one of your webinars before! This is where I first got into optics.

I mostly like them, but I hate the hieroglyphics. I had some previous success hacking my way through it with a custom infix operator ( ^ ) and using [<RequireQualifiedAccess>], so my optics looked something like

Optic.modify (First.list ^ TryNth.listItem n) (fun elem -> makePurple elem) document

Similarly, Optic.set, Optic.get, Optic.toList, GetAll, SetAll/ModifyAll and also a Where.attrName (Where type queries is when the bugs started to show up)

Anyways, thanks for posting.