Elm 标记联合类型比较构造函数

Elm Tagged Union Type compare constructor

在Elm中是否可以使用==来比较tagged union类型的构造函数,还是必须用case?

示例:

  type alias Model =
    { accessToken : String
    , page : Page
    , config : Config 
    } 

  type Page 
    = Home String
    | Profile String


   menu : Model -> Html Msg
   menu model = 
      div []
          [ a [ href "#home", classList [ ("active", model.page == Home) ] ][ text "Home" ]
          , a [ href "#profile", classList [ ("active", model.page == Profile)] ][ text "Profile" ]        
          ]

在示例中,我想写类似 model.page == Home 的代码来检查当前页面是否为主页,这样我就可以将 css class 设置为"active" 关于 link,但似乎我必须为此使用一个案例,我可以这样做,但对于这种情况实施起来有点尴尬。

不,您不能使用 == 检查哪个构造函数用于创建标记的联合值。我们通常这样做的方式是通过一些辅助函数:

isHome : Page -> Bool
isHome pg =
    case pg of
        Home _ -> True
        _ -> False

isProfile : Page -> Bool
isProfile pg =
    case pg of
        Profile _ -> True
        _ -> False

这会在调用时生成同样可读的代码:

menu : Model -> Html Msg
menu model =
    div []
        [ a [ href "#home", classList [ ( "active", isHome model.page ) ] ] [ text "Home" ]
        , a [ href "#profile", classList [ ( "active", isProfile model.page ) ] ] [ text "Profile" ]
        ]