Elm 联合子集

Elm union subsets

假设我有一个这样的联合类型:

type Route
  = Home
  | License
  | UserProfile { username : String }
  | Search { query : String }
  | SomeOtherPage

在实践中,我经常需要使用这个联合的 子集 。例如:

type StaticRoute = Home | License

我希望能够定义接受上述子集的函数,而不是更广泛的 Route

我不想在 Route 中嵌套 StaticRoute,像这样:

type Route
  = Static StaticRoute
  | UserProfile { username : String }
  | Search { query : String }
  | SomeOtherPage

这是因为我希望能够定义 Route 的许多不同子集,其中一些可能重叠:

type StaticRoute = Home | License
type RouteWithServerRendering = Home | Search { query : String }
type LoggedInRoute = SomeOtherPage
-- and so on…

那我如何定义 Route 的子集而不重复定义?

Jasper Woudenberg 最近发布 转换函数,五颗星 ,提倡具有相似的类型并使用转换函数将一种类型转换为另一种类型。

在你的情况下,它可能看起来像这样:

module Route exposing (fromStaticRoute, toStaticRoute)

fromStaticRoute : StaticRoute -> Route
fromStaticRoute staticRoute =
    case staticRoute of
        Static.Home ->
            Home
        Static.License ->
            License

toStaticRoute : Route -> Maybe StaticRoute
toStaticRoute route =
    case route of
        Home ->
            Just Static.Home
        License ->
            Just Static.License
        _ ->
            Nothing