SlideShare a Scribd company logo

Template Haskell Tutorial

K
kizzx2
1 of 25
Download to read offline
Template Haskell Tutorial

                                      short, illustrated examples
         from Illustrated Haskell <http://illustratedhaskell.org>
Motivating example
    fst(x,_)      = x
    fst3(x,_,_)   = x
    fst4(x,_,_,_) = x
    …

    print $ fst3 ("hello world", 1, 2)
    print $ fst4 ("hello world", 1, 2, 3)

So repetitive!


    Illustrated Haskell <http://illustratedhaskell.org>
Template Haskell to the rescue!
Usage:

    {-# LANGUAGE TemplateHaskell #-}
    print $ $(fstN 3) ("hello world", 1, 2)
    print $ $(fstN 4) ("hello world", 1, 2, 3)




    Illustrated Haskell <http://illustratedhaskell.org>
How to write it?
-- FstN.hs
{-# LANGUAGE TemplateHaskell #-}
module FstN where
import Language.Haskell.TH

fstN :: Q Exp
fstN n = do
    x <- newName "x”
    return $ LamE [TupP $
        VarP x : replicate (n-1) WildP] (VarE x)


Illustrated Haskell <http://illustratedhaskell.org>
OK, how about explaining it?
 Every time you want to write something in TH, you start with:
runQ [| ... |]

    GHC will tell you how to write it. For example, if we wanted to
      write a splice that will produce (x,_,_) -> x

$ ghci – fth
> :m +Language.Haskell.TH
> runQ [| (x,_,_) -> x |]
LamE [TupP [VarP x_1,WildP,WildP]] (VarE x_1)
> :t it
it :: Exp

    That’s it, no need to remember anything! Just ask GHC!

    Illustrated Haskell <http://illustratedhaskell.org>
Writing fst3 in TH
 So we already have an Exp, how about those x_1?
LamE [TupP [VarP x_1,WildP,WildP]] (VarE x_1)

> :t (VarP, VarE)
(VarP, VarE) :: (Name -> Pat, Name -> Exp)

 So, VarP and VarE takes a Name. Let’s see how we can satisfy
    them:
> :t newName
newName :: String -> Q Name

    A ha! So we can just plug it into the expression GHC gave us:
fst3 = do
    x <- newName "x"
    LamE [TupP [VarP x,WildP,WildP]] (VarE x)

    Illustrated Haskell <http://illustratedhaskell.org>

Recommended

Limitations of memory system performance
Limitations of memory system performanceLimitations of memory system performance
Limitations of memory system performanceSyed Zaid Irshad
 
Compilers and interpreters
Compilers and interpretersCompilers and interpreters
Compilers and interpretersRAJU KATHI
 
Memory consistency models
Memory consistency modelsMemory consistency models
Memory consistency modelspalani kumar
 
Processes Control Block (Operating System)
Processes Control Block (Operating System)Processes Control Block (Operating System)
Processes Control Block (Operating System)Imdad Ullah
 
LiveBindings: desde lo básico hasta técnicas avanzadas
LiveBindings: desde lo básico hasta técnicas avanzadas LiveBindings: desde lo básico hasta técnicas avanzadas
LiveBindings: desde lo básico hasta técnicas avanzadas Fernando Rizzato
 

More Related Content

What's hot

Register transfer language
Register transfer languageRegister transfer language
Register transfer languageSanjeev Patel
 
Computer Network Notes UNIT II
Computer Network Notes UNIT IIComputer Network Notes UNIT II
Computer Network Notes UNIT IINANDINI SHARMA
 
CS4109 Computer System Architecture
CS4109 Computer System ArchitectureCS4109 Computer System Architecture
CS4109 Computer System Architecturektosri
 
Interfacing With High Level Programming Language
Interfacing With High Level Programming Language Interfacing With High Level Programming Language
Interfacing With High Level Programming Language .AIR UNIVERSITY ISLAMABAD
 
Open mp library functions and environment variables
Open mp library functions and environment variablesOpen mp library functions and environment variables
Open mp library functions and environment variablesSuveeksha
 
Introduction To Computer Programming
Introduction To Computer ProgrammingIntroduction To Computer Programming
Introduction To Computer ProgrammingHussain Buksh
 
Input Output - Computer Architecture
Input Output - Computer ArchitectureInput Output - Computer Architecture
Input Output - Computer ArchitectureMaruf Abdullah (Rion)
 
Lecture 1 introduction to parallel and distributed computing
Lecture 1   introduction to parallel and distributed computingLecture 1   introduction to parallel and distributed computing
Lecture 1 introduction to parallel and distributed computingVajira Thambawita
 
Register transfer language & its micro operations
Register transfer language & its micro operationsRegister transfer language & its micro operations
Register transfer language & its micro operationsLakshya Sharma
 
Threads and multi threading
Threads and multi threadingThreads and multi threading
Threads and multi threadingAntonio Cesarano
 

What's hot (20)

Register transfer language
Register transfer languageRegister transfer language
Register transfer language
 
Computer Network Notes UNIT II
Computer Network Notes UNIT IIComputer Network Notes UNIT II
Computer Network Notes UNIT II
 
CS4109 Computer System Architecture
CS4109 Computer System ArchitectureCS4109 Computer System Architecture
CS4109 Computer System Architecture
 
Micro operations
Micro operationsMicro operations
Micro operations
 
Interfacing With High Level Programming Language
Interfacing With High Level Programming Language Interfacing With High Level Programming Language
Interfacing With High Level Programming Language
 
OPERATING SYSTEM
OPERATING SYSTEMOPERATING SYSTEM
OPERATING SYSTEM
 
5. protocol layering
5. protocol layering5. protocol layering
5. protocol layering
 
Distributed systems scheduling
Distributed systems schedulingDistributed systems scheduling
Distributed systems scheduling
 
Computer system bus
Computer system busComputer system bus
Computer system bus
 
Open mp library functions and environment variables
Open mp library functions and environment variablesOpen mp library functions and environment variables
Open mp library functions and environment variables
 
Introduction To Computer Programming
Introduction To Computer ProgrammingIntroduction To Computer Programming
Introduction To Computer Programming
 
Cpu & its execution of instruction
Cpu & its execution of instructionCpu & its execution of instruction
Cpu & its execution of instruction
 
c_programming
c_programmingc_programming
c_programming
 
Input Output - Computer Architecture
Input Output - Computer ArchitectureInput Output - Computer Architecture
Input Output - Computer Architecture
 
Lecture 1 introduction to parallel and distributed computing
Lecture 1   introduction to parallel and distributed computingLecture 1   introduction to parallel and distributed computing
Lecture 1 introduction to parallel and distributed computing
 
Os Threads
Os ThreadsOs Threads
Os Threads
 
Register transfer language & its micro operations
Register transfer language & its micro operationsRegister transfer language & its micro operations
Register transfer language & its micro operations
 
ns-3 Tutorial
ns-3 Tutorialns-3 Tutorial
ns-3 Tutorial
 
Threads and multi threading
Threads and multi threadingThreads and multi threading
Threads and multi threading
 
Processes and threads
Processes and threadsProcesses and threads
Processes and threads
 

Similar to Template Haskell Tutorial

Javascript variables and datatypes
Javascript variables and datatypesJavascript variables and datatypes
Javascript variables and datatypesVarun C M
 
Haxe: What Makes It Cool
Haxe: What Makes It CoolHaxe: What Makes It Cool
Haxe: What Makes It CooleddieSullivan
 
Java script
 Java script Java script
Java scriptbosybosy
 
Xslate sv perl-2013-7-11
Xslate sv perl-2013-7-11Xslate sv perl-2013-7-11
Xslate sv perl-2013-7-11Goro Fuji
 
10. session 10 loops and arrays
10. session 10   loops and arrays10. session 10   loops and arrays
10. session 10 loops and arraysPhúc Đỗ
 
Library functions in c++
Library functions in c++Library functions in c++
Library functions in c++Neeru Mittal
 
Big Data Everywhere Chicago: Unleash the Power of HBase Shell (Conversant)
Big Data Everywhere Chicago: Unleash the Power of HBase Shell (Conversant) Big Data Everywhere Chicago: Unleash the Power of HBase Shell (Conversant)
Big Data Everywhere Chicago: Unleash the Power of HBase Shell (Conversant) BigDataEverywhere
 
PHP and MySQL with snapshots
 PHP and MySQL with snapshots PHP and MySQL with snapshots
PHP and MySQL with snapshotsrichambra
 
Rewriting Java In Scala
Rewriting Java In ScalaRewriting Java In Scala
Rewriting Java In ScalaSkills Matter
 
Introduction to PowerShell
Introduction to PowerShellIntroduction to PowerShell
Introduction to PowerShellSalaudeen Rajack
 
Handout - Introduction to Programming
Handout - Introduction to ProgrammingHandout - Introduction to Programming
Handout - Introduction to ProgrammingCindy Royal
 
Haskell retrospective
Haskell retrospectiveHaskell retrospective
Haskell retrospectivechenge2k
 
Regular expressions, Session and Cookies by Dr.C.R.Dhivyaa Kongu Engineering ...
Regular expressions, Session and Cookies by Dr.C.R.Dhivyaa Kongu Engineering ...Regular expressions, Session and Cookies by Dr.C.R.Dhivyaa Kongu Engineering ...
Regular expressions, Session and Cookies by Dr.C.R.Dhivyaa Kongu Engineering ...Dhivyaa C.R
 

Similar to Template Haskell Tutorial (20)

Javascript variables and datatypes
Javascript variables and datatypesJavascript variables and datatypes
Javascript variables and datatypes
 
Haxe: What Makes It Cool
Haxe: What Makes It CoolHaxe: What Makes It Cool
Haxe: What Makes It Cool
 
Unfiltered Unveiled
Unfiltered UnveiledUnfiltered Unveiled
Unfiltered Unveiled
 
Template Haskell
Template HaskellTemplate Haskell
Template Haskell
 
Java script
 Java script Java script
Java script
 
Xslate sv perl-2013-7-11
Xslate sv perl-2013-7-11Xslate sv perl-2013-7-11
Xslate sv perl-2013-7-11
 
10. session 10 loops and arrays
10. session 10   loops and arrays10. session 10   loops and arrays
10. session 10 loops and arrays
 
Library functions in c++
Library functions in c++Library functions in c++
Library functions in c++
 
PHP-Part3
PHP-Part3PHP-Part3
PHP-Part3
 
Scala - brief intro
Scala - brief introScala - brief intro
Scala - brief intro
 
Recursion Lecture in C++
Recursion Lecture in C++Recursion Lecture in C++
Recursion Lecture in C++
 
PHP PPT FILE
PHP PPT FILEPHP PPT FILE
PHP PPT FILE
 
Javascript
JavascriptJavascript
Javascript
 
Big Data Everywhere Chicago: Unleash the Power of HBase Shell (Conversant)
Big Data Everywhere Chicago: Unleash the Power of HBase Shell (Conversant) Big Data Everywhere Chicago: Unleash the Power of HBase Shell (Conversant)
Big Data Everywhere Chicago: Unleash the Power of HBase Shell (Conversant)
 
PHP and MySQL with snapshots
 PHP and MySQL with snapshots PHP and MySQL with snapshots
PHP and MySQL with snapshots
 
Rewriting Java In Scala
Rewriting Java In ScalaRewriting Java In Scala
Rewriting Java In Scala
 
Introduction to PowerShell
Introduction to PowerShellIntroduction to PowerShell
Introduction to PowerShell
 
Handout - Introduction to Programming
Handout - Introduction to ProgrammingHandout - Introduction to Programming
Handout - Introduction to Programming
 
Haskell retrospective
Haskell retrospectiveHaskell retrospective
Haskell retrospective
 
Regular expressions, Session and Cookies by Dr.C.R.Dhivyaa Kongu Engineering ...
Regular expressions, Session and Cookies by Dr.C.R.Dhivyaa Kongu Engineering ...Regular expressions, Session and Cookies by Dr.C.R.Dhivyaa Kongu Engineering ...
Regular expressions, Session and Cookies by Dr.C.R.Dhivyaa Kongu Engineering ...
 

Recently uploaded

Cultivating Entrepreneurial Mindset in Product Management: Strategies for Suc...
Cultivating Entrepreneurial Mindset in Product Management: Strategies for Suc...Cultivating Entrepreneurial Mindset in Product Management: Strategies for Suc...
Cultivating Entrepreneurial Mindset in Product Management: Strategies for Suc...Product School
 
Transcript: Trending now: Book subjects on the move in the Canadian market - ...
Transcript: Trending now: Book subjects on the move in the Canadian market - ...Transcript: Trending now: Book subjects on the move in the Canadian market - ...
Transcript: Trending now: Book subjects on the move in the Canadian market - ...BookNet Canada
 
Harnessing the Power of GenAI for Exceptional Product Outcomes by Booking.com...
Harnessing the Power of GenAI for Exceptional Product Outcomes by Booking.com...Harnessing the Power of GenAI for Exceptional Product Outcomes by Booking.com...
Harnessing the Power of GenAI for Exceptional Product Outcomes by Booking.com...Product School
 
PrismCRM-RealEstate-SalesCRM_byCode5Company
PrismCRM-RealEstate-SalesCRM_byCode5CompanyPrismCRM-RealEstate-SalesCRM_byCode5Company
PrismCRM-RealEstate-SalesCRM_byCode5CompanyMustafa Kuğu
 
Synergy in Leadership and Product Excellence: A Blueprint for Growth by CPO, ...
Synergy in Leadership and Product Excellence: A Blueprint for Growth by CPO, ...Synergy in Leadership and Product Excellence: A Blueprint for Growth by CPO, ...
Synergy in Leadership and Product Excellence: A Blueprint for Growth by CPO, ...Product School
 
How We Grew Up with CloudStack and its Journey – Dilip Singh, DataHub
How We Grew Up with CloudStack and its Journey – Dilip Singh, DataHubHow We Grew Up with CloudStack and its Journey – Dilip Singh, DataHub
How We Grew Up with CloudStack and its Journey – Dilip Singh, DataHubShapeBlue
 
Unleash the Solace Pub Sub connector | Banaglore MuleSoft Meetup #31
Unleash the Solace Pub Sub connector | Banaglore MuleSoft Meetup #31Unleash the Solace Pub Sub connector | Banaglore MuleSoft Meetup #31
Unleash the Solace Pub Sub connector | Banaglore MuleSoft Meetup #31shyamraj55
 
Learning About GenAI Engineering with AWS PartyRock [AWS User Group Basel - F...
Learning About GenAI Engineering with AWS PartyRock [AWS User Group Basel - F...Learning About GenAI Engineering with AWS PartyRock [AWS User Group Basel - F...
Learning About GenAI Engineering with AWS PartyRock [AWS User Group Basel - F...Chris Bingham
 
Progress Report: Ministry of IT under Dr. Umar Saif Aug 23-Feb'24
Progress Report: Ministry of IT under Dr. Umar Saif Aug 23-Feb'24Progress Report: Ministry of IT under Dr. Umar Saif Aug 23-Feb'24
Progress Report: Ministry of IT under Dr. Umar Saif Aug 23-Feb'24Umar Saif
 
VM Migration from VMware to CloudStack and KVM – Suresh Anaparti, ShapeBlue
VM Migration from VMware to CloudStack and KVM – Suresh Anaparti, ShapeBlueVM Migration from VMware to CloudStack and KVM – Suresh Anaparti, ShapeBlue
VM Migration from VMware to CloudStack and KVM – Suresh Anaparti, ShapeBlueShapeBlue
 
National Institute of Standards and Technology (NIST) Cybersecurity Framework...
National Institute of Standards and Technology (NIST) Cybersecurity Framework...National Institute of Standards and Technology (NIST) Cybersecurity Framework...
National Institute of Standards and Technology (NIST) Cybersecurity Framework...MichaelBenis1
 
Confoo 2024 Gettings started with OpenAI and data science
Confoo 2024 Gettings started with OpenAI and data scienceConfoo 2024 Gettings started with OpenAI and data science
Confoo 2024 Gettings started with OpenAI and data scienceSusan Ibach
 
CloudStack Tooling Ecosystem – Kiran Chavala, ShapeBlue
CloudStack Tooling Ecosystem – Kiran Chavala, ShapeBlueCloudStack Tooling Ecosystem – Kiran Chavala, ShapeBlue
CloudStack Tooling Ecosystem – Kiran Chavala, ShapeBlueShapeBlue
 
Revolutionizing The Banking Industry: The Monzo Way by CPO, Monzo
Revolutionizing The Banking Industry: The Monzo Way by CPO, MonzoRevolutionizing The Banking Industry: The Monzo Way by CPO, Monzo
Revolutionizing The Banking Industry: The Monzo Way by CPO, MonzoProduct School
 
How to write an effective Cyber Incident Response Plan
How to write an effective Cyber Incident Response PlanHow to write an effective Cyber Incident Response Plan
How to write an effective Cyber Incident Response PlanDatabarracks
 
iOncologi_Pitch Deck_2024 slide show for hostinger
iOncologi_Pitch Deck_2024 slide show for hostingeriOncologi_Pitch Deck_2024 slide show for hostinger
iOncologi_Pitch Deck_2024 slide show for hostingerssuser9354ce
 
Trending now: Book subjects on the move in the Canadian market - Tech Forum 2024
Trending now: Book subjects on the move in the Canadian market - Tech Forum 2024Trending now: Book subjects on the move in the Canadian market - Tech Forum 2024
Trending now: Book subjects on the move in the Canadian market - Tech Forum 2024BookNet Canada
 
Geospatial Synergy: Amplifying Efficiency with FME & Esri
Geospatial Synergy: Amplifying Efficiency with FME & EsriGeospatial Synergy: Amplifying Efficiency with FME & Esri
Geospatial Synergy: Amplifying Efficiency with FME & EsriSafe Software
 
CloudStack 101: The Best Way to Build Your Private Cloud – Rohit Yadav, VP Ap...
CloudStack 101: The Best Way to Build Your Private Cloud – Rohit Yadav, VP Ap...CloudStack 101: The Best Way to Build Your Private Cloud – Rohit Yadav, VP Ap...
CloudStack 101: The Best Way to Build Your Private Cloud – Rohit Yadav, VP Ap...ShapeBlue
 

Recently uploaded (20)

Cultivating Entrepreneurial Mindset in Product Management: Strategies for Suc...
Cultivating Entrepreneurial Mindset in Product Management: Strategies for Suc...Cultivating Entrepreneurial Mindset in Product Management: Strategies for Suc...
Cultivating Entrepreneurial Mindset in Product Management: Strategies for Suc...
 
Transcript: Trending now: Book subjects on the move in the Canadian market - ...
Transcript: Trending now: Book subjects on the move in the Canadian market - ...Transcript: Trending now: Book subjects on the move in the Canadian market - ...
Transcript: Trending now: Book subjects on the move in the Canadian market - ...
 
Harnessing the Power of GenAI for Exceptional Product Outcomes by Booking.com...
Harnessing the Power of GenAI for Exceptional Product Outcomes by Booking.com...Harnessing the Power of GenAI for Exceptional Product Outcomes by Booking.com...
Harnessing the Power of GenAI for Exceptional Product Outcomes by Booking.com...
 
PrismCRM-RealEstate-SalesCRM_byCode5Company
PrismCRM-RealEstate-SalesCRM_byCode5CompanyPrismCRM-RealEstate-SalesCRM_byCode5Company
PrismCRM-RealEstate-SalesCRM_byCode5Company
 
Synergy in Leadership and Product Excellence: A Blueprint for Growth by CPO, ...
Synergy in Leadership and Product Excellence: A Blueprint for Growth by CPO, ...Synergy in Leadership and Product Excellence: A Blueprint for Growth by CPO, ...
Synergy in Leadership and Product Excellence: A Blueprint for Growth by CPO, ...
 
In sharing we trust. Taking advantage of a diverse consortium to build a tran...
In sharing we trust. Taking advantage of a diverse consortium to build a tran...In sharing we trust. Taking advantage of a diverse consortium to build a tran...
In sharing we trust. Taking advantage of a diverse consortium to build a tran...
 
How We Grew Up with CloudStack and its Journey – Dilip Singh, DataHub
How We Grew Up with CloudStack and its Journey – Dilip Singh, DataHubHow We Grew Up with CloudStack and its Journey – Dilip Singh, DataHub
How We Grew Up with CloudStack and its Journey – Dilip Singh, DataHub
 
Unleash the Solace Pub Sub connector | Banaglore MuleSoft Meetup #31
Unleash the Solace Pub Sub connector | Banaglore MuleSoft Meetup #31Unleash the Solace Pub Sub connector | Banaglore MuleSoft Meetup #31
Unleash the Solace Pub Sub connector | Banaglore MuleSoft Meetup #31
 
Learning About GenAI Engineering with AWS PartyRock [AWS User Group Basel - F...
Learning About GenAI Engineering with AWS PartyRock [AWS User Group Basel - F...Learning About GenAI Engineering with AWS PartyRock [AWS User Group Basel - F...
Learning About GenAI Engineering with AWS PartyRock [AWS User Group Basel - F...
 
Progress Report: Ministry of IT under Dr. Umar Saif Aug 23-Feb'24
Progress Report: Ministry of IT under Dr. Umar Saif Aug 23-Feb'24Progress Report: Ministry of IT under Dr. Umar Saif Aug 23-Feb'24
Progress Report: Ministry of IT under Dr. Umar Saif Aug 23-Feb'24
 
VM Migration from VMware to CloudStack and KVM – Suresh Anaparti, ShapeBlue
VM Migration from VMware to CloudStack and KVM – Suresh Anaparti, ShapeBlueVM Migration from VMware to CloudStack and KVM – Suresh Anaparti, ShapeBlue
VM Migration from VMware to CloudStack and KVM – Suresh Anaparti, ShapeBlue
 
National Institute of Standards and Technology (NIST) Cybersecurity Framework...
National Institute of Standards and Technology (NIST) Cybersecurity Framework...National Institute of Standards and Technology (NIST) Cybersecurity Framework...
National Institute of Standards and Technology (NIST) Cybersecurity Framework...
 
Confoo 2024 Gettings started with OpenAI and data science
Confoo 2024 Gettings started with OpenAI and data scienceConfoo 2024 Gettings started with OpenAI and data science
Confoo 2024 Gettings started with OpenAI and data science
 
CloudStack Tooling Ecosystem – Kiran Chavala, ShapeBlue
CloudStack Tooling Ecosystem – Kiran Chavala, ShapeBlueCloudStack Tooling Ecosystem – Kiran Chavala, ShapeBlue
CloudStack Tooling Ecosystem – Kiran Chavala, ShapeBlue
 
Revolutionizing The Banking Industry: The Monzo Way by CPO, Monzo
Revolutionizing The Banking Industry: The Monzo Way by CPO, MonzoRevolutionizing The Banking Industry: The Monzo Way by CPO, Monzo
Revolutionizing The Banking Industry: The Monzo Way by CPO, Monzo
 
How to write an effective Cyber Incident Response Plan
How to write an effective Cyber Incident Response PlanHow to write an effective Cyber Incident Response Plan
How to write an effective Cyber Incident Response Plan
 
iOncologi_Pitch Deck_2024 slide show for hostinger
iOncologi_Pitch Deck_2024 slide show for hostingeriOncologi_Pitch Deck_2024 slide show for hostinger
iOncologi_Pitch Deck_2024 slide show for hostinger
 
Trending now: Book subjects on the move in the Canadian market - Tech Forum 2024
Trending now: Book subjects on the move in the Canadian market - Tech Forum 2024Trending now: Book subjects on the move in the Canadian market - Tech Forum 2024
Trending now: Book subjects on the move in the Canadian market - Tech Forum 2024
 
Geospatial Synergy: Amplifying Efficiency with FME & Esri
Geospatial Synergy: Amplifying Efficiency with FME & EsriGeospatial Synergy: Amplifying Efficiency with FME & Esri
Geospatial Synergy: Amplifying Efficiency with FME & Esri
 
CloudStack 101: The Best Way to Build Your Private Cloud – Rohit Yadav, VP Ap...
CloudStack 101: The Best Way to Build Your Private Cloud – Rohit Yadav, VP Ap...CloudStack 101: The Best Way to Build Your Private Cloud – Rohit Yadav, VP Ap...
CloudStack 101: The Best Way to Build Your Private Cloud – Rohit Yadav, VP Ap...
 

Template Haskell Tutorial

  • 1. Template Haskell Tutorial short, illustrated examples from Illustrated Haskell <http://illustratedhaskell.org>
  • 2. Motivating example  fst(x,_) = x  fst3(x,_,_) = x  fst4(x,_,_,_) = x  …  print $ fst3 ("hello world", 1, 2)  print $ fst4 ("hello world", 1, 2, 3) So repetitive! Illustrated Haskell <http://illustratedhaskell.org>
  • 3. Template Haskell to the rescue! Usage:  {-# LANGUAGE TemplateHaskell #-}  print $ $(fstN 3) ("hello world", 1, 2)  print $ $(fstN 4) ("hello world", 1, 2, 3) Illustrated Haskell <http://illustratedhaskell.org>
  • 4. How to write it? -- FstN.hs {-# LANGUAGE TemplateHaskell #-} module FstN where import Language.Haskell.TH fstN :: Q Exp fstN n = do x <- newName "x” return $ LamE [TupP $ VarP x : replicate (n-1) WildP] (VarE x) Illustrated Haskell <http://illustratedhaskell.org>
  • 5. OK, how about explaining it?  Every time you want to write something in TH, you start with: runQ [| ... |]  GHC will tell you how to write it. For example, if we wanted to write a splice that will produce (x,_,_) -> x $ ghci – fth > :m +Language.Haskell.TH > runQ [| (x,_,_) -> x |] LamE [TupP [VarP x_1,WildP,WildP]] (VarE x_1) > :t it it :: Exp  That’s it, no need to remember anything! Just ask GHC! Illustrated Haskell <http://illustratedhaskell.org>
  • 6. Writing fst3 in TH  So we already have an Exp, how about those x_1? LamE [TupP [VarP x_1,WildP,WildP]] (VarE x_1) > :t (VarP, VarE) (VarP, VarE) :: (Name -> Pat, Name -> Exp)  So, VarP and VarE takes a Name. Let’s see how we can satisfy them: > :t newName newName :: String -> Q Name  A ha! So we can just plug it into the expression GHC gave us: fst3 = do x <- newName "x" LamE [TupP [VarP x,WildP,WildP]] (VarE x) Illustrated Haskell <http://illustratedhaskell.org>
  • 7. Evolving fst3 into fstN  The following corresponds to the expression (x,_,_) -> x fst3 = do x <- newName "x" LamE [TupP [VarP x,WildP,WildP]] (VarE x)  Not surprisingly, to make fst4, we just need to make 3 WildP: fst4 = do x <- newName "x" LamE [TupP [VarP x,WildP,WildP,WildP]] (VarE x)  And we can easily generalize it into fstN fstN n = do x <- newName "x" LamE [TupP (VarP x : replicate (n-1) WildP)] (VarE x) Illustrated Haskell <http://illustratedhaskell.org>
  • 8. Using fstN  For technical reasons, splices must be defined in a separate module.  So we need to create a new module to use the splice we defined: -- TestFstN.hs main = print $ $(fstN 3) ("hello world", 1, 3) Illustrated Haskell <http://illustratedhaskell.org>
  • 10. Quasi Quotes  The [| … |] notation that you just used is the quasi quotes for Haskell expression.  The contents within quasi quotes will be parsed at compile time.  Example: in Data.Array.Repa.Stencil, you could define a stencil like this [stencil2| 0 1 0 1 0 1 0 1 0 |]  It is converted to: makeStencil2 (Z:.3:.3) (ix -> case ix of Z :. -1 :. 0 -> Just 1 Z :. 0 :. -1 -> Just 1 Z :. 0 :. 1 -> Just 1 Z :. 1 :. 0 -> Just 1 _ -> Nothing) Illustrated Haskell <http://illustratedhaskell.org>
  • 11. Quasi Quotes  When you do [| x -> x |], the string inside the brackets is parsed by the Haskell compiler and gives you back the AST (Abstract Syntax Tree) Illustrated Haskell <http://illustratedhaskell.org>
  • 12. Let’s do a simple example  We will build a structure to represent HTML documents  For simplicity, we omit attributes, self closing tags, etc. -- HTML.hs {-# LANGUAGE TemplateHaskell, QuasiQuotes #-} module HTML where data Node = Tag String [Node] -- tag name, children | Text String deriving Show  Our target is to use quasi quotes to build a document tree: -- HTMLTest.hs import HTML doc :: Node doc = [html|<html>Hello, <strong>TH</strong> world!</html>] -- Node "html" [Text "Hello, ”, Tag "strong" [Text "TH"], Text " world!"] Illustrated Haskell <http://illustratedhaskell.org>
  • 13. First, a simple HTML parser  We’ll sidetrack a bit and make a dead simple HTML parser using Parsec  Our focus here isn’t Parsec so we can just skim over this function that does the right thing -- HTML.hs textNode :: Parser Node textNode = fmap Text $ many1 $ satisfy (/='<') tagNode :: Parser Node tagNode = do tagName <- char '<' *> many1 letter <* char '>' children <- many $ try tagNode <|> textNode string "</" >> string tagName >> char '>' return $ Tag tagName children Illustrated Haskell <http://illustratedhaskell.org>
  • 14. A simple test for our parser $ ghci HTML.hs > parseTest tagNode "<html>Hello, <strong>TH</strong> world!</html>" Tag "html" [Text "Hello, ",Tag "strong" [Text "TH"],Text " world!”]  It works! Illustrated Haskell <http://illustratedhaskell.org>
  • 15. Now we can write our QuasiQuoter -- HTML.hs  The QuasiQuoter takes 4 Html :: QuasiQuoter parameters. Each will be called when the quasi quote Html = QuasiQuoter is being invoked to create: htmlExpr  An expression undefined  foo = [html| ... |]  A pattern (for pattern undefined matching) undefined  bar [html| ... |] = 3  A type  A top-level declaration htmlExpr :: String -> Q Exp htmlExpr = undefined  We will do expression and pattern in this example  For more information consult GHC’s documentation Illustrated Haskell <http://illustratedhaskell.org>
  • 16. htmlExpr is supposed to parse the contents within [html| … |] and give back an Exp htmlExpr :: String -> Q Exp htmlExpr str = do filename <- loc_filename `fmap` location case parse tagNode filename str of Left err -> undefined Right tag -> [| tag |]  As easy as that, loc_filename and location will give us the filename of the user. Illustrated Haskell <http://illustratedhaskell.org>
  • 17. Let’s compile it! $ ghc HTML.hs Error: No instance for (Lift Node) arising from arising of `tag’…  What is that? Well maybe we can satisfy it by implementing the Lift instance for Node, as instructed: instance Lift Node where lift (Text t) = [| Text t |] lift (Tag name children) = [| Tag name children |] Illustrated Haskell <http://illustratedhaskell.org>
  • 18. Let’s try it out -- HTMLTest.hs {-# LANGUAGE TemplateHaskell , QuasiQuotes #-} import HTML main = print [html|<html>Hello, <strong>TH</strong> world!</html>|] $ ghci HTMLTest.hs > main Tag "html" [Text "Hello, ",Tag "strong" [Text "TH"],Text " world!"]  It works!  Illustrated Haskell <http://illustratedhaskell.org>
  • 19. Quasi quoting for patterns  Now let’s try to do some operations on our HTML structure  In this example we will convert an HTML tree into Markdown  Markdown is a simple wiki syntax  Example Markdown: Let’s **rock** and _roll_!  Corresponding HTML: <html>Let's <strong>rock</strong> and <em>roll</em></html>  Usually people convert Markdown to HTML. We will do it the other way here. Illustrated Haskell <http://illustratedhaskell.org>
  • 20. Let’s make a simple converter -- HTMLTest.hs markdown (Tag "strong" children) = "**" ++ concatMap markdown children ++ "**" markdown (Tag "em" children) = "_" ++ concatMap markdown children ++ "_" markdown (Tag _ children) = concatMap markdown children markdown (Text t) = t  That’s some normal Haskell. For fun, we’re going to turn it into: -- HTMLTest.hs markdown [html|<strong>|] = "**" ++ concatMap markdown children ++ "**" markdown [html|<em>|] = "_" ++ concatMap markdown children ++ "_" markdown [html|<_>|] = concatMap markdown children markdown [html|#text|] = text  Are we gaining anything? Honestly not much. But we’ll do it for the sake of an TH example. Illustrated Haskell <http://illustratedhaskell.org>
  • 21. Add a pattern parser to our QuasiQuoter -- HTML.hs html :: QuasiQuoter html = QuasiQuoter htmlExpr htmlPat undefined undefined htmlPat :: String -> Q Pat htmlPat "<_>" = [p| Tag _ children |] htmlPat "#text" = [p| Text text |] htmlPat ('<':rest) = undefined -- ... Illustrated Haskell <http://illustratedhaskell.org>
  • 22. Asking GHC again…  Now how do we write the “rest” case? Let’s ask GHC > runQ [p| Tag "strong" chlidren |] ConP HTML.Tag [ LitP (StringL "strong") , VarP chlidren]  So there we have almost had it.  We just need to use Name at appropriate places and follow the types: htmlPat ('<':rest) = return $ ConP (mkName "HTML.Tag”) [ LitP (StringL (init rest)) , VarP (mkName "children")] Illustrated Haskell <http://illustratedhaskell.org>
  • 23. Some explanations htmlPat ('<':rest) = return $ ConP (mkName "HTML.Tag”) [ LitP (StringL (init rest)) , VarP (mkName "children")]  Here we see mkName intead of newName  mkName "foo" will translate into an identifier "foo" literally  mkName "foo" will become something like "foo_1".  You’ll use this when you want to avoid name collisions Illustrated Haskell <http://illustratedhaskell.org>
  • 24. Let’s test it out! -- HTMLTest.hs {-# LANGUAGE TemplateHaskell , QuasiQuotes #-} import HTML doc = [html|<html>Hello, <strong>TH</strong> world!</html>|] markdown [html|<_>|] = concatMap markdown children markdown [html|#text|] = text markdown [html|<strong>|] = "**" ++ concatMap markdown children ++ "**” main = print . markdown $ doc  $ runhaskell HTMLTest.hs  "Hello, **TH** world!" Illustrated Haskell <http://illustratedhaskell.org>
  • 25. Summary  Use runQ to have GHC write the splice for you  Then just fix it up by following the type Illustrated Haskell <http://illustratedhaskell.org>