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.
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" ]
]
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With