jw3126 / Setfield.jl

Update deeply nested immutable structs.
Other
167 stars 17 forks source link

`haslens` analog to`hasfield` #145

Open goretkin opened 4 years ago

goretkin commented 4 years ago

I didn't see an existing way to check whether get(obj, l) would return a value or throw any or all of

ERROR: type $obj has no field $f BoundsError ArgumentError: invalid index: $i

etc.

It could be nice to have a function or two for this. Possibly two so that one can do all the "static" checks---no bounds checking on AbstractArrays with non-inferrable size, or keys in Dicts)

jw3126 commented 4 years ago

Thanks! I agree it would be nice to have this. I think this is basically Base.hasmethod(get, Tuple{typeof(obj), typeof(lens)}). Sadly that is not static at the moment. I also think the lens case is no easier then the general Base.hasmethod. Just think about FunctionLens. Also ComposedLens seems pretty hard and it is absolutely essential. So I see no other way than wait for some bright day, where hasmethod is static.

tkf commented 4 years ago

Is it important that you can do haslens or is it OK to have a non-failing lens? As discussed in #65, we can have a lens that returns Union{Some{T},Nothing} to express possibly non-existing locations. A cool feature is that we can also use this to remove the location as well (which, of course, works only with something like Dict and NamedTuple).

I guess we can have a lens transformation to automatically lift a lens to the safe/"maybe" version. Something like get(obj, maybe(@lens _.a.b[:c])).