0

Can i create data haskell with a help of Template Haskell. Data like :

data Shape = Circle [Float] Double Int

I want write a program, which create Data and then use it

Vincent Savard
  • 34,979
  • 10
  • 68
  • 73
Ivan
  • 85
  • 6
  • Try and provide a working example (it doesn't need to compile!) or more context to motivate the question. – hao Mar 25 '16 at 17:48
  • @haoformayor I actually think his question is well formulated, and writing any Template Haskell is quite a burden.... There is very little information available. It took me days before I could write even the simplest working snippet. – jamshidh Mar 25 '16 at 18:52
  • Just put it inside a splice: `[d| data Shape = Circle [Float] Double Int |]` will do the trick. – user2407038 Mar 25 '16 at 22:09

1 Answers1

0

Here is a minimal example (sorry, I've never figured out how to make template haskell look pretty)....

First, create a library file (this isn't optional, TH requires you to define expressions in a separate file).

module DataDefinition where

import Language.Haskell.TH

dataDef::DecsQ
dataDef = do
  return $ --the following is the definition "data Shape = Circle Float | Square"
        [DataD 
                [] 
                (mkName "shape") 
                [] 
                [
                        NormalC (mkName "circle") 
                                [(NotStrict, ConT (mkName "Float"))],
                        NormalC (mkName "Square") []
                ] 
                []
        ]

Then, use it like this

module Main where

import DataDefinition

$(dataDef)  --This defines Shape

main = do
  let x = Circle 1.0 --Now you can define and use Shape like any other data def....
  return ()

extra-

You can fill in that last empty array in the DataD creation with deriving instances.... Try changing the [] to

          [mkName "Show"]

and you can print the output in main....

main = do
  let x = Circle 1.0
  print x
jamshidh
  • 12,002
  • 17
  • 31