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.

1 Answer 1

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) []
Sign up to request clarification or add additional context in comments.

1 Comment

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"

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.