0

Similar to this question, but even more runtime-ey.

Is there a way to automatically generate lenses, or any other mechanism, for accessing fields by name at runtime?

I'm looking for something similar to field from generic-lens, except taking the field name as a runtime argument instead of a type-leve parameter (and returning a Maybe).

I'm comfortable enough writing this myself, but I think it probably already exists.

Example

data Foo = Foo { bar :: Bar }
data Bar = ...

Deriving Generic, you can use generic-lens to get the handy field @"bar" lens - but is there any way to automatically generate/derive a fieldAtRuntime "bar" which behaves the same (or a similar) way?

Motivation

I want to navigate some custom data structures using JSON paths. It doesn't really matter to me that the JSON might not match up exactly with the record fields, but I do want to not have to serialize, traverse, and de-serialize.

Isaac van Bakel
  • 1,772
  • 10
  • 22
  • I actually doubt that this exists, because **a)** it seems pretty un-idiomatic **b)** as you said it can be done, and maybe _should_ be done, on a (by nature dynamic) Aeson type, rather than a typed Haskell ADT. – leftaroundabout Feb 21 '20 at 16:21
  • It's only my motivation that brings in the Aeson consideration. Without it, this question is more "has someone already written some TH to derive an `Indexable String` instance for records which does the right thing?". – Isaac van Bakel Feb 21 '20 at 17:19
  • Yes, but unless you're doing something JSON-ish, I don't see a good reason why you'd want such an instance. Source code details such as field names aren't really supposed to exist at runtime (the default behaviour of `Show`/`Read` notwithstanding, but those are mostly debugging helpers). – leftaroundabout Feb 21 '20 at 17:22

0 Answers0