2014-05-01 13 views
7

Supponiamo che io sono un tipo di dati in questo modo:definizioni di funzioni multiple con template Haskell

data Color = Red | Blue | Green 

Come dovrei generare una funzione come questa utilizzando templatehaskell?

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

Ad esempio, sto cercando più definizioni per una funzione basata sulla corrispondenza del modello.

risposta

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) [] 
+0

Questo mi ha messo sulla strada giusta. Ho finito per usare un lambda con un'espressione case come questa: 'myShow = return $ LamE [VarP mc] (CaseE (VarE mc) $ [Match ...] dove mc = mkName" mc "' –

Problemi correlati