title: Generic way to cast union to Maybe of its component types
body: <p>I have a union type that looks like this:</p>
  <pre><code>type User
      = Admin ComplicatedAdminRecord
      . . .
      | NormalUser ComplicatedUserRecord
  </code></pre>
  <p>I'm looking for a <em>generic</em> way to filter a <code>List User</code> into (possibly empty) <code>List</code>s of the union's component types.</p>
  <p>What I have <em>works</em>, 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:</p>
  <pre><code>asMaybeAdmin : User -&gt; Maybe ComplicatedAdminRecord
  asMaybeAdmin user =
      case user of
          Admin adminUser -&gt;
              Just adminUser
  
          _ -&gt;
              Nothing
  
  onlyAdmins =
      List.filterMap asMaybeAdmin users
  </code></pre>
  <p>This is fine if you only have one type that you're trying to filter for, but having to write a new <code>asMaybe&lt;Type&gt;</code> for each component type is a lot of repetition that I feel like I should be able to write generically.</p>