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

标签 elm union-types

是否可以使用 ==比较 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 类设置为“事件”,但似乎我必须使用一个案例,我可以做,但在这种情况下实现有点尴尬。

最佳答案

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

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

关于Elm 标记联合类型比较构造函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48884126/

相关文章:

functional-programming - 为什么我们在Elm函数组合中不指定参数?

haskell - 在 Haskell 中,如果 Maybe 是一个类型或一个联合类型,你怎么称呼 `Nothing` ?

typescript - 如何从对象键的嵌套对象创建映射的联合类型

typescript - 如何从 typescript 中的标记联合类型中提取类型?

elm - 如何创建 Signal x -> x 类型的函数?

elm - 错误处理和信号

Elm 架构和任务

Typescript - 联合类型

arrays - PowerShell 中是否提供联合类型

json - 如何在 Elm 中编码和解码简单的自定义类型?