是否可以在 Haskell 中先编写包罗万象的模式?还是使用“否定”模式?

问题描述

有时,如果模式规则需要一些特殊的rhs,通过where使其更具可读性,我最终会得到这样的东西

data D = A | B | C
func :: D -> b
func A = special_case
  where
    special_case = other helper
    other = aaaa
    helper = bbb
func _ = bla

由于 where 很长,所以包罗万象的模式似乎与其他模式相去甚远。如果我能写出这样的东西就好了:

func :: D -> b
func !A = bla -- imaginary Syntax
func A = special_case
  where
    special_case = other helper
    other = aaaa
    helper = bbb

我不认为它仍然会被称为“全能”,而是“全能但”,但有什么办法可以做到这一点吗?

解决方法

如果你不需要绑定任何东西,你可以这样做:

isA :: D -> Bool
isA A = True
isA _ = False

func :: D -> b
func d | not (isA d) = bla
func A = special_case where ...

(你也可以实现 isn'tA 来避免 not。但是虽然我经常看到像 isA 这样定义的函数,但我相信我从来没有见过isn'tA 的类比。)

对于编译器来说,这个匹配是否完成可能并不明显。你可以这样解决:

type A'sFields = () -- your specific D doesn't have any fields for A,-- but this pattern is general enough to use for
                    -- constructors that do

fromA :: D -> Maybe A'sFields
fromA A = Just ()
fromA _ = Nothing

func :: D -> b
func d = case fromA d of
    Nothing -> bla
    Just () -> special_case where ...