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

Is it a bad idea to use custom binary data types in Haskell?

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

data MyType = Constructor1 | Constructor2 deriving Eq

是的,这种类型实际上与 Bool 相同,我只是将其命名为不同的名称以使我的代码更具可读性。在程序的后面,我有

形式的函数
myFunc input = if input == Constructor1 then --do something
    else --do something else

我认为这可能是个坏主意的原因是,如果按原样解释,程序每次遇到此分支时都必须 运行 通过 [=它为 MyType 设置的 14=] 函数得到一个 Bool 传递给 if_then_else_ 函数,而如果我刚刚使用 Bool == 功能被消除,这将加快进程。

我应该用 Bool 的实例替换 MyType 的所有实例还是 ghc 以某种方式优化这些数据类型的使用?

不,不要将其替换为 Bool;而是用模式匹配替换相等性检查。

myFunc Constructor1 = -- do something
myFunc Constructor2 = -- do something else

丹尼尔方法的一些替代方法(无论如何,这是最好的方法)。

  • 使用case .. of

    myFunc input = case input of
       Constructor1 -> ...
       Constructor2 -> ...
    
  • 滚动您的自定义 if(Haskell 擅长于此!)

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