How to examine a quoted data constructor name in Template Haskell?

前端 未结 1 1723
孤街浪徒
孤街浪徒 2021-01-14 05:52

I\'m trying to learn some Template Haskell. As an exercise, I wrote a function that can generate things like isLeft and isRight (inspired by this q

相关标签:
1条回答
  • 2021-01-14 06:23

    While you could use reify and examine the type to determine the arity of the data constructor, it's much easier to generate arity-independent code using a record pattern:

    isFoo :: Bar -> Bool
    isFoo p = case p of
        (Foo {}) -> True     -- Valid no matter what the arity of Foo is
        _        -> False
    

    This can be done by replacing conP with recP in your code.

    isA connam = do
        ConE nam <- connam
        nn <- newName "p"
        lamE [varP nn] $ caseE (varE nn) [
                           match (recP nam []) ( normalB [| True |] ) [],
                           match wildP ( normalB [| False |] ) [] 
                         ]
    
    0 讨论(0)
提交回复
热议问题