【问题标题】:Elm Tagged Union Type compare constructorElm Tagged Union Type 比较构造函数
【发布时间】:2018-02-20 22:58:14
【问题描述】:

是否可以使用==比较Elm中标记联合类型的构造函数,还是必须用例?

例子:

  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 类设置为“活动”,但似乎我必须为此使用一个案例,我可以这样做,但对于这种情况实施有点尴尬。

【问题讨论】:

    标签: elm union-types


    【解决方案1】:

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

    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" ]
            ]
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-09-29
      • 1970-01-01
      相关资源
      最近更新 更多