s3cur3
s3cur3

Reputation: 3025

Generic way to cast union to Maybe of its component types

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) Lists 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

Answers (1)

user12026681
user12026681

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

  • try it out
    elm-review --template lue-bird/elm-review-missing-record-field-lens/example/variant-helpers-simple
    
  • source code

There are similar projects that you might wanna look at but don't offer variant accessing, yet:

Upvotes: 1

Related Questions