Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 843
Xyking Avatar asked Feb 20 '18 11:02

Xyking


1 Answers

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" ]
        ]
like image 149
Chad Gilbert Avatar answered Sep 20 '22 23:09

Chad Gilbert