Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Multiple function definitions with template haskell

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.

like image 979
Vlad the Impala Avatar asked May 01 '14 00:05

Vlad the Impala


1 Answers

{-# 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) []
like image 196
user2407038 Avatar answered Sep 28 '22 07:09

user2407038