Defining TH Lift instances for algebraic data types

haskell, template-haskell

Solution

This is the purpose of the th-lift package, which provides exactly this functionality: http://hackage.haskell.org/package/th-lift

Problem

Suppose I have an algebraic data type with multiple constructors, like ``` data Animal a = Mouse a | Beaver a | Rabbit a ``` How would I create a `Lift` instance effectively? The easiest way of doing so would be ``` instance (Lift a) => Lift (Animal a) where lift (Mouse x) = [| Mouse x |] lift (Beaver x) = [| Beaver x |] lift (Rabbit x) = [| Rabbit x |] ``` This is very redundant though. Of course I can't directly abstract the different animals away like `lift x = [| x |]`, although conceptually that's similar to what I want to achieve. Is there a way of doing this in TH so that I don't have to write the same line again for each data constructor?

Original source