Reputation: 3025
I have a union type that looks like this:
type User
= Admin ComplicatedAdminRecord
. . .
| NormalUser ComplicatedUserRecord
I'm looking for a generic way to filter a List User
into (possibly empty) List
s of the union's component types.
What I have works, but it's horrible and the amount of copypasta code is linear in the number of types I'm trying to filter on. It looks like this:
asMaybeAdmin : User -> Maybe ComplicatedAdminRecord
asMaybeAdmin user =
case user of
Admin adminUser ->
Just adminUser
_ ->
Nothing
onlyAdmins =
List.filterMap asMaybeAdmin users
This is fine if you only have one type that you're trying to filter for, but having to write a new asMaybe<Type>
for each component type is a lot of repetition that I feel like I should be able to write generically.
Upvotes: 1
Views: 114
Reputation:
You can auto-generate variant helpers via elm-review
.
Out of the box, you can generate "prisms" (these combine multiple helpers: access, alter, name)
but implementing simpler helpers is also possible! ↓ implements toVariant
access functions
elm-review --template lue-bird/elm-review-missing-record-field-lens/example/variant-helpers-simple
There are similar projects that you might wanna look at but don't offer variant accessing, yet:
Upvotes: 1