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

8

在Elm中,是否可以使用==来比较标记联合类型的构造函数,还是必须使用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 的东西来检查当前页面是否为Home,这样我就可以将该链接的css类设置为“active”,但是似乎我必须为此使用case语句,虽然我可以做到,但对于这种情况来说有点笨拙。
1个回答

9
不可以使用==检查用于创建标记联合值的构造函数。通常我们会通过一些辅助函数来完成这个任务:
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" ]
        ]

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接