Xyking
Xyking

Reputation: 83

Elm Tagged Union Type compare constructor

Is it possible to use == to compare the constructor of tagged union types in Elm, or do you have to use case?

Example:

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

In the example, I would like to write something like model.page == Home to check if the current page is Home, so that I can set the css class to "active" on that link, but it seems like I have to use a case for it, which I can do, but is kinda akward to implement for this situation.

Upvotes: 8

Views: 497

Answers (1)

Chad Gilbert
Chad Gilbert

Reputation: 36375

No, you cannot use == to check which constructor was used to create a tagged union value. The way we typically do this is through some helper functions:

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

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

This leads to equally readable code when called:

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

Upvotes: 9

Related Questions