7

Suppose I have a data type like so:

data Color = Red | Blue | Green

How would I generate a function like this using templatehaskell?

myShow Red   = ...
myShow Blue  = ...
myShow Green = ...

i.e. I'm looking for multiple definitions for a function based on pattern-matching.

Alex Celeste
  • 12,824
  • 10
  • 46
  • 89
Vlad the Impala
  • 15,572
  • 16
  • 81
  • 124

1 Answers1

3
{-# LANGUAGE TemplateHaskell #-}

module Test where 

import Language.Haskell.TH

data Color = Red | Blue | Green

myShow' :: Q [Dec]
myShow' = return [FunD (mkName "myShow") [mkClause 'Red, mkClause 'Blue, mkClause 'Green]]
  where mkClause n = Clause [ConP n []] (NormalB $ LitE $ StringL $ nameBase n) []
user2407038
  • 14,400
  • 3
  • 29
  • 42
  • This put me on the right track. I ended up using a lambda with a case expression like so: `myShow = return $ LamE [VarP mc] (CaseE (VarE mc) $ [Match ...] where mc = mkName "mc"` – Vlad the Impala May 01 '14 at 05:26