榆树工会子集

Oli*_*Ash 3 elm union-types

说我有一个像这样的联合类型:

type Route
  = Home
  | License
  | UserProfile { username : String }
  | Search { query : String }
  | SomeOtherPage
Run Code Online (Sandbox Code Playgroud)

在实践中,我经常需要处理此联合的子集。例如:

type StaticRoute = Home | License
Run Code Online (Sandbox Code Playgroud)

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

我不想窝StaticRouteRoute,像这样:

type Route
  = Static StaticRoute
  | UserProfile { username : String }
  | Search { query : String }
  | SomeOtherPage
Run Code Online (Sandbox Code Playgroud)

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

type StaticRoute = Home | License
type RouteWithServerRendering = Home | Search { query : String }
type LoggedInRoute = SomeOtherPage
-- and so on…
Run Code Online (Sandbox Code Playgroud)

那如何在Route不重复定义的情况下定义的子集呢?

bdu*_*kes 7

贾斯珀·伍登伯格(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
Run Code Online (Sandbox Code Playgroud)