代码之家  ›  专栏  ›  技术社区  ›  Eben Kadile

在Haskell中使用自定义二进制数据类型是个坏主意吗?

  •  2
  • Eben Kadile  · 技术社区  · 7 年前

    最近,我制作了一个程序,其中使用了以下形式的数据类型:

    data MyType = Constructor1 | Constructor2 deriving Eq
    

    是的,这种类型实际上与 Bool

    myFunc input = if input == Constructor1 then --do something
        else --do something else
    

    我认为这可能是一个坏主意的原因是,如果它只是按现在的方式解释,那么每次程序遇到这个分支时,它都必须通过 == 为其设置的功能 MyType 获得 传递给 if_then_else_ 函数,而如果我刚刚使用 必要性 ==

    我应该替换的所有实例吗 我的类型 具有以下实例: 布尔 还是ghc以某种方式优化了此类数据类型的使用?

    2 回复  |  直到 7 年前
        1
  •  8
  •   Daniel Wagner    7 年前

    不,不要用 Bool

    myFunc Constructor1 = -- do something
    myFunc Constructor2 = -- do something else
    
        2
  •  2
  •   chi    7 年前

    • 使用 case .. of

      myFunc input = case input of
         Constructor1 -> ...
         Constructor2 -> ...
      
    • if (哈斯克尔擅长于此!)

      -- define this helper once
      myIf :: MyType -> a -> a -> a
      myIf Constructor1 x1 _  = x1
      myIf Constructor2 _  x2 = x2
      
      -- use it as many times as needed
      myFunc input = myIf input
         (...) -- "then"/Constructor1 branch
         (...) -- "else"/Constructor2 branch