“Pattern matching” of algebraic type data constructors

后端 未结 5 1775
天涯浪人
天涯浪人 2021-02-07 15:07

Let\'s consider a data type with many constructors:

data T = Alpha Int | Beta Int | Gamma Int Int | Delta Int

I want to write a function to che

5条回答
  •  情书的邮戳
    2021-02-07 15:54

    You'll need to use a generics library like Scrap Your Boilerplate or uniplate to do this in general.

    If you don't want to be so heavy-handed, you can use Dave Hinton's solution, together with the empty record shortcut:

    ...
    where f (Alpha {}) = 0
          f (Beta {}) = 1
          f (Gamma {}) = 2
    

    So you don't have to know how many args each constructor has. But it obviously still leaves something to be desired.

提交回复
热议问题